xref: /llvm-project/lldb/source/Commands/CommandObjectThread.cpp (revision 04a4c0910b08fcd3961ad8cc74f99535efdee39a)
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     Process *process = m_exe_ctx.GetProcessPtr();
823     if (process == nullptr) {
824       result.AppendError("no process exists. Cannot continue");
825       result.SetStatus(eReturnStatusFailed);
826       return false;
827     }
828 
829     StateType state = process->GetState();
830     if ((state == eStateCrashed) || (state == eStateStopped) ||
831         (state == eStateSuspended)) {
832       const size_t argc = command.GetArgumentCount();
833       if (argc > 0) {
834         // These two lines appear at the beginning of both blocks in this
835         // if..else, but that is because we need to release the lock before
836         // calling process->Resume below.
837         std::lock_guard<std::recursive_mutex> guard(
838             process->GetThreadList().GetMutex());
839         const uint32_t num_threads = process->GetThreadList().GetSize();
840         std::vector<Thread *> resume_threads;
841         for (auto &entry : command.entries()) {
842           uint32_t thread_idx;
843           if (entry.ref.getAsInteger(0, thread_idx)) {
844             result.AppendErrorWithFormat(
845                 "invalid thread index argument: \"%s\".\n", entry.c_str());
846             result.SetStatus(eReturnStatusFailed);
847             return false;
848           }
849           Thread *thread =
850               process->GetThreadList().FindThreadByIndexID(thread_idx).get();
851 
852           if (thread) {
853             resume_threads.push_back(thread);
854           } else {
855             result.AppendErrorWithFormat("invalid thread index %u.\n",
856                                          thread_idx);
857             result.SetStatus(eReturnStatusFailed);
858             return false;
859           }
860         }
861 
862         if (resume_threads.empty()) {
863           result.AppendError("no valid thread indexes were specified");
864           result.SetStatus(eReturnStatusFailed);
865           return false;
866         } else {
867           if (resume_threads.size() == 1)
868             result.AppendMessageWithFormat("Resuming thread: ");
869           else
870             result.AppendMessageWithFormat("Resuming threads: ");
871 
872           for (uint32_t idx = 0; idx < num_threads; ++idx) {
873             Thread *thread =
874                 process->GetThreadList().GetThreadAtIndex(idx).get();
875             std::vector<Thread *>::iterator this_thread_pos =
876                 find(resume_threads.begin(), resume_threads.end(), thread);
877 
878             if (this_thread_pos != resume_threads.end()) {
879               resume_threads.erase(this_thread_pos);
880               if (!resume_threads.empty())
881                 result.AppendMessageWithFormat("%u, ", thread->GetIndexID());
882               else
883                 result.AppendMessageWithFormat("%u ", thread->GetIndexID());
884 
885               const bool override_suspend = true;
886               thread->SetResumeState(eStateRunning, override_suspend);
887             } else {
888               thread->SetResumeState(eStateSuspended);
889             }
890           }
891           result.AppendMessageWithFormat("in process %" PRIu64 "\n",
892                                          process->GetID());
893         }
894       } else {
895         // These two lines appear at the beginning of both blocks in this
896         // if..else, but that is because we need to release the lock before
897         // calling process->Resume below.
898         std::lock_guard<std::recursive_mutex> guard(
899             process->GetThreadList().GetMutex());
900         const uint32_t num_threads = process->GetThreadList().GetSize();
901         Thread *current_thread = GetDefaultThread();
902         if (current_thread == nullptr) {
903           result.AppendError("the process doesn't have a current thread");
904           result.SetStatus(eReturnStatusFailed);
905           return false;
906         }
907         // Set the actions that the threads should each take when resuming
908         for (uint32_t idx = 0; idx < num_threads; ++idx) {
909           Thread *thread = process->GetThreadList().GetThreadAtIndex(idx).get();
910           if (thread == current_thread) {
911             result.AppendMessageWithFormat("Resuming thread 0x%4.4" PRIx64
912                                            " in process %" PRIu64 "\n",
913                                            thread->GetID(), process->GetID());
914             const bool override_suspend = true;
915             thread->SetResumeState(eStateRunning, override_suspend);
916           } else {
917             thread->SetResumeState(eStateSuspended);
918           }
919         }
920       }
921 
922       StreamString stream;
923       Status error;
924       if (synchronous_execution)
925         error = process->ResumeSynchronous(&stream);
926       else
927         error = process->Resume();
928 
929       // We should not be holding the thread list lock when we do this.
930       if (error.Success()) {
931         result.AppendMessageWithFormat("Process %" PRIu64 " resuming\n",
932                                        process->GetID());
933         if (synchronous_execution) {
934           // If any state changed events had anything to say, add that to the
935           // result
936           if (stream.GetSize() > 0)
937             result.AppendMessage(stream.GetString());
938 
939           result.SetDidChangeProcessState(true);
940           result.SetStatus(eReturnStatusSuccessFinishNoResult);
941         } else {
942           result.SetStatus(eReturnStatusSuccessContinuingNoResult);
943         }
944       } else {
945         result.AppendErrorWithFormat("Failed to resume process: %s\n",
946                                      error.AsCString());
947         result.SetStatus(eReturnStatusFailed);
948       }
949     } else {
950       result.AppendErrorWithFormat(
951           "Process cannot be continued from its current state (%s).\n",
952           StateAsCString(state));
953       result.SetStatus(eReturnStatusFailed);
954     }
955 
956     return result.Succeeded();
957   }
958 };
959 
960 // CommandObjectThreadUntil
961 
962 static constexpr OptionEnumValueElement g_duo_running_mode[] = {
963     {eOnlyThisThread, "this-thread", "Run only this thread"},
964     {eAllThreads, "all-threads", "Run all threads"} };
965 
966 static constexpr OptionEnumValues DuoRunningModes() {
967   return OptionEnumValues(g_duo_running_mode);
968 }
969 
970 #define LLDB_OPTIONS_thread_until
971 #include "CommandOptions.inc"
972 
973 class CommandObjectThreadUntil : public CommandObjectParsed {
974 public:
975   class CommandOptions : public Options {
976   public:
977     uint32_t m_thread_idx;
978     uint32_t m_frame_idx;
979 
980     CommandOptions()
981         : Options(), m_thread_idx(LLDB_INVALID_THREAD_ID),
982           m_frame_idx(LLDB_INVALID_FRAME_ID) {
983       // Keep default values of all options in one place: OptionParsingStarting
984       // ()
985       OptionParsingStarting(nullptr);
986     }
987 
988     ~CommandOptions() override = default;
989 
990     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
991                           ExecutionContext *execution_context) override {
992       Status error;
993       const int short_option = m_getopt_table[option_idx].val;
994 
995       switch (short_option) {
996       case 'a': {
997         lldb::addr_t tmp_addr = OptionArgParser::ToAddress(
998             execution_context, option_arg, LLDB_INVALID_ADDRESS, &error);
999         if (error.Success())
1000           m_until_addrs.push_back(tmp_addr);
1001       } break;
1002       case 't':
1003         if (option_arg.getAsInteger(0, m_thread_idx)) {
1004           m_thread_idx = LLDB_INVALID_INDEX32;
1005           error.SetErrorStringWithFormat("invalid thread index '%s'",
1006                                          option_arg.str().c_str());
1007         }
1008         break;
1009       case 'f':
1010         if (option_arg.getAsInteger(0, m_frame_idx)) {
1011           m_frame_idx = LLDB_INVALID_FRAME_ID;
1012           error.SetErrorStringWithFormat("invalid frame index '%s'",
1013                                          option_arg.str().c_str());
1014         }
1015         break;
1016       case 'm': {
1017         auto enum_values = GetDefinitions()[option_idx].enum_values;
1018         lldb::RunMode run_mode = (lldb::RunMode)OptionArgParser::ToOptionEnum(
1019             option_arg, enum_values, eOnlyDuringStepping, error);
1020 
1021         if (error.Success()) {
1022           if (run_mode == eAllThreads)
1023             m_stop_others = false;
1024           else
1025             m_stop_others = true;
1026         }
1027       } break;
1028       default:
1029         llvm_unreachable("Unimplemented option");
1030       }
1031       return error;
1032     }
1033 
1034     void OptionParsingStarting(ExecutionContext *execution_context) override {
1035       m_thread_idx = LLDB_INVALID_THREAD_ID;
1036       m_frame_idx = 0;
1037       m_stop_others = false;
1038       m_until_addrs.clear();
1039     }
1040 
1041     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
1042       return llvm::makeArrayRef(g_thread_until_options);
1043     }
1044 
1045     uint32_t m_step_thread_idx;
1046     bool m_stop_others;
1047     std::vector<lldb::addr_t> m_until_addrs;
1048 
1049     // Instance variables to hold the values for command options.
1050   };
1051 
1052   CommandObjectThreadUntil(CommandInterpreter &interpreter)
1053       : CommandObjectParsed(
1054             interpreter, "thread until",
1055             "Continue until a line number or address is reached by the "
1056             "current or specified thread.  Stops when returning from "
1057             "the current function as a safety measure.  "
1058             "The target line number(s) are given as arguments, and if more than one"
1059             " is provided, stepping will stop when the first one is hit.",
1060             nullptr,
1061             eCommandRequiresThread | eCommandTryTargetAPILock |
1062                 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused),
1063         m_options() {
1064     CommandArgumentEntry arg;
1065     CommandArgumentData line_num_arg;
1066 
1067     // Define the first (and only) variant of this arg.
1068     line_num_arg.arg_type = eArgTypeLineNum;
1069     line_num_arg.arg_repetition = eArgRepeatPlain;
1070 
1071     // There is only one variant this argument could be; put it into the
1072     // argument entry.
1073     arg.push_back(line_num_arg);
1074 
1075     // Push the data for the first argument into the m_arguments vector.
1076     m_arguments.push_back(arg);
1077   }
1078 
1079   ~CommandObjectThreadUntil() override = default;
1080 
1081   Options *GetOptions() override { return &m_options; }
1082 
1083 protected:
1084   bool DoExecute(Args &command, CommandReturnObject &result) override {
1085     bool synchronous_execution = m_interpreter.GetSynchronous();
1086 
1087     Target *target = &GetSelectedTarget();
1088 
1089     Process *process = m_exe_ctx.GetProcessPtr();
1090     if (process == nullptr) {
1091       result.AppendError("need a valid process to step");
1092       result.SetStatus(eReturnStatusFailed);
1093     } else {
1094       Thread *thread = nullptr;
1095       std::vector<uint32_t> line_numbers;
1096 
1097       if (command.GetArgumentCount() >= 1) {
1098         size_t num_args = command.GetArgumentCount();
1099         for (size_t i = 0; i < num_args; i++) {
1100           uint32_t line_number;
1101           line_number = StringConvert::ToUInt32(command.GetArgumentAtIndex(i),
1102                                                 UINT32_MAX);
1103           if (line_number == UINT32_MAX) {
1104             result.AppendErrorWithFormat("invalid line number: '%s'.\n",
1105                                          command.GetArgumentAtIndex(i));
1106             result.SetStatus(eReturnStatusFailed);
1107             return false;
1108           } else
1109             line_numbers.push_back(line_number);
1110         }
1111       } else if (m_options.m_until_addrs.empty()) {
1112         result.AppendErrorWithFormat("No line number or address provided:\n%s",
1113                                      GetSyntax().str().c_str());
1114         result.SetStatus(eReturnStatusFailed);
1115         return false;
1116       }
1117 
1118       if (m_options.m_thread_idx == LLDB_INVALID_THREAD_ID) {
1119         thread = GetDefaultThread();
1120       } else {
1121         thread = process->GetThreadList()
1122                      .FindThreadByIndexID(m_options.m_thread_idx)
1123                      .get();
1124       }
1125 
1126       if (thread == nullptr) {
1127         const uint32_t num_threads = process->GetThreadList().GetSize();
1128         result.AppendErrorWithFormat(
1129             "Thread index %u is out of range (valid values are 0 - %u).\n",
1130             m_options.m_thread_idx, num_threads);
1131         result.SetStatus(eReturnStatusFailed);
1132         return false;
1133       }
1134 
1135       const bool abort_other_plans = false;
1136 
1137       StackFrame *frame =
1138           thread->GetStackFrameAtIndex(m_options.m_frame_idx).get();
1139       if (frame == nullptr) {
1140         result.AppendErrorWithFormat(
1141             "Frame index %u is out of range for thread %u.\n",
1142             m_options.m_frame_idx, m_options.m_thread_idx);
1143         result.SetStatus(eReturnStatusFailed);
1144         return false;
1145       }
1146 
1147       ThreadPlanSP new_plan_sp;
1148       Status new_plan_status;
1149 
1150       if (frame->HasDebugInformation()) {
1151         // Finally we got here...  Translate the given line number to a bunch
1152         // of addresses:
1153         SymbolContext sc(frame->GetSymbolContext(eSymbolContextCompUnit));
1154         LineTable *line_table = nullptr;
1155         if (sc.comp_unit)
1156           line_table = sc.comp_unit->GetLineTable();
1157 
1158         if (line_table == nullptr) {
1159           result.AppendErrorWithFormat("Failed to resolve the line table for "
1160                                        "frame %u of thread index %u.\n",
1161                                        m_options.m_frame_idx,
1162                                        m_options.m_thread_idx);
1163           result.SetStatus(eReturnStatusFailed);
1164           return false;
1165         }
1166 
1167         LineEntry function_start;
1168         uint32_t index_ptr = 0, end_ptr;
1169         std::vector<addr_t> address_list;
1170 
1171         // Find the beginning & end index of the
1172         AddressRange fun_addr_range = sc.function->GetAddressRange();
1173         Address fun_start_addr = fun_addr_range.GetBaseAddress();
1174         line_table->FindLineEntryByAddress(fun_start_addr, function_start,
1175                                            &index_ptr);
1176 
1177         Address fun_end_addr(fun_start_addr.GetSection(),
1178                              fun_start_addr.GetOffset() +
1179                                  fun_addr_range.GetByteSize());
1180 
1181         bool all_in_function = true;
1182 
1183         line_table->FindLineEntryByAddress(fun_end_addr, function_start,
1184                                            &end_ptr);
1185 
1186         for (uint32_t line_number : line_numbers) {
1187           uint32_t start_idx_ptr = index_ptr;
1188           while (start_idx_ptr <= end_ptr) {
1189             LineEntry line_entry;
1190             const bool exact = false;
1191             start_idx_ptr = sc.comp_unit->FindLineEntry(
1192                 start_idx_ptr, line_number, sc.comp_unit, exact, &line_entry);
1193             if (start_idx_ptr == UINT32_MAX)
1194               break;
1195 
1196             addr_t address =
1197                 line_entry.range.GetBaseAddress().GetLoadAddress(target);
1198             if (address != LLDB_INVALID_ADDRESS) {
1199               if (fun_addr_range.ContainsLoadAddress(address, target))
1200                 address_list.push_back(address);
1201               else
1202                 all_in_function = false;
1203             }
1204             start_idx_ptr++;
1205           }
1206         }
1207 
1208         for (lldb::addr_t address : m_options.m_until_addrs) {
1209           if (fun_addr_range.ContainsLoadAddress(address, target))
1210             address_list.push_back(address);
1211           else
1212             all_in_function = false;
1213         }
1214 
1215         if (address_list.empty()) {
1216           if (all_in_function)
1217             result.AppendErrorWithFormat(
1218                 "No line entries matching until target.\n");
1219           else
1220             result.AppendErrorWithFormat(
1221                 "Until target outside of the current function.\n");
1222 
1223           result.SetStatus(eReturnStatusFailed);
1224           return false;
1225         }
1226 
1227         new_plan_sp = thread->QueueThreadPlanForStepUntil(
1228             abort_other_plans, &address_list.front(), address_list.size(),
1229             m_options.m_stop_others, m_options.m_frame_idx, new_plan_status);
1230         if (new_plan_sp) {
1231           // User level plans should be master plans so they can be interrupted
1232           // (e.g. by hitting a breakpoint) and other plans executed by the
1233           // user (stepping around the breakpoint) and then a "continue" will
1234           // resume the original plan.
1235           new_plan_sp->SetIsMasterPlan(true);
1236           new_plan_sp->SetOkayToDiscard(false);
1237         } else {
1238           result.SetError(new_plan_status);
1239           result.SetStatus(eReturnStatusFailed);
1240           return false;
1241         }
1242       } else {
1243         result.AppendErrorWithFormat(
1244             "Frame index %u of thread %u has no debug information.\n",
1245             m_options.m_frame_idx, m_options.m_thread_idx);
1246         result.SetStatus(eReturnStatusFailed);
1247         return false;
1248       }
1249 
1250       process->GetThreadList().SetSelectedThreadByID(m_options.m_thread_idx);
1251 
1252       StreamString stream;
1253       Status error;
1254       if (synchronous_execution)
1255         error = process->ResumeSynchronous(&stream);
1256       else
1257         error = process->Resume();
1258 
1259       if (error.Success()) {
1260         result.AppendMessageWithFormat("Process %" PRIu64 " resuming\n",
1261                                        process->GetID());
1262         if (synchronous_execution) {
1263           // If any state changed events had anything to say, add that to the
1264           // result
1265           if (stream.GetSize() > 0)
1266             result.AppendMessage(stream.GetString());
1267 
1268           result.SetDidChangeProcessState(true);
1269           result.SetStatus(eReturnStatusSuccessFinishNoResult);
1270         } else {
1271           result.SetStatus(eReturnStatusSuccessContinuingNoResult);
1272         }
1273       } else {
1274         result.AppendErrorWithFormat("Failed to resume process: %s.\n",
1275                                      error.AsCString());
1276         result.SetStatus(eReturnStatusFailed);
1277       }
1278     }
1279     return result.Succeeded();
1280   }
1281 
1282   CommandOptions m_options;
1283 };
1284 
1285 // CommandObjectThreadSelect
1286 
1287 class CommandObjectThreadSelect : public CommandObjectParsed {
1288 public:
1289   CommandObjectThreadSelect(CommandInterpreter &interpreter)
1290       : CommandObjectParsed(interpreter, "thread select",
1291                             "Change the currently selected thread.", nullptr,
1292                             eCommandRequiresProcess | eCommandTryTargetAPILock |
1293                                 eCommandProcessMustBeLaunched |
1294                                 eCommandProcessMustBePaused) {
1295     CommandArgumentEntry arg;
1296     CommandArgumentData thread_idx_arg;
1297 
1298     // Define the first (and only) variant of this arg.
1299     thread_idx_arg.arg_type = eArgTypeThreadIndex;
1300     thread_idx_arg.arg_repetition = eArgRepeatPlain;
1301 
1302     // There is only one variant this argument could be; put it into the
1303     // argument entry.
1304     arg.push_back(thread_idx_arg);
1305 
1306     // Push the data for the first argument into the m_arguments vector.
1307     m_arguments.push_back(arg);
1308   }
1309 
1310   ~CommandObjectThreadSelect() override = default;
1311 
1312 protected:
1313   bool DoExecute(Args &command, CommandReturnObject &result) override {
1314     Process *process = m_exe_ctx.GetProcessPtr();
1315     if (process == nullptr) {
1316       result.AppendError("no process");
1317       result.SetStatus(eReturnStatusFailed);
1318       return false;
1319     } else if (command.GetArgumentCount() != 1) {
1320       result.AppendErrorWithFormat(
1321           "'%s' takes exactly one thread index argument:\nUsage: %s\n",
1322           m_cmd_name.c_str(), m_cmd_syntax.c_str());
1323       result.SetStatus(eReturnStatusFailed);
1324       return false;
1325     }
1326 
1327     uint32_t index_id =
1328         StringConvert::ToUInt32(command.GetArgumentAtIndex(0), 0, 0);
1329 
1330     Thread *new_thread =
1331         process->GetThreadList().FindThreadByIndexID(index_id).get();
1332     if (new_thread == nullptr) {
1333       result.AppendErrorWithFormat("invalid thread #%s.\n",
1334                                    command.GetArgumentAtIndex(0));
1335       result.SetStatus(eReturnStatusFailed);
1336       return false;
1337     }
1338 
1339     process->GetThreadList().SetSelectedThreadByID(new_thread->GetID(), true);
1340     result.SetStatus(eReturnStatusSuccessFinishNoResult);
1341 
1342     return result.Succeeded();
1343   }
1344 };
1345 
1346 // CommandObjectThreadList
1347 
1348 class CommandObjectThreadList : public CommandObjectParsed {
1349 public:
1350   CommandObjectThreadList(CommandInterpreter &interpreter)
1351       : CommandObjectParsed(
1352             interpreter, "thread list",
1353             "Show a summary of each thread in the current target process.  "
1354             "Use 'settings set thread-format' to customize the individual "
1355             "thread listings.",
1356             "thread list",
1357             eCommandRequiresProcess | eCommandTryTargetAPILock |
1358                 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused) {}
1359 
1360   ~CommandObjectThreadList() override = default;
1361 
1362 protected:
1363   bool DoExecute(Args &command, CommandReturnObject &result) override {
1364     Stream &strm = result.GetOutputStream();
1365     result.SetStatus(eReturnStatusSuccessFinishNoResult);
1366     Process *process = m_exe_ctx.GetProcessPtr();
1367     const bool only_threads_with_stop_reason = false;
1368     const uint32_t start_frame = 0;
1369     const uint32_t num_frames = 0;
1370     const uint32_t num_frames_with_source = 0;
1371     process->GetStatus(strm);
1372     process->GetThreadStatus(strm, only_threads_with_stop_reason, start_frame,
1373                              num_frames, num_frames_with_source, false);
1374     return result.Succeeded();
1375   }
1376 };
1377 
1378 // CommandObjectThreadInfo
1379 #define LLDB_OPTIONS_thread_info
1380 #include "CommandOptions.inc"
1381 
1382 class CommandObjectThreadInfo : public CommandObjectIterateOverThreads {
1383 public:
1384   class CommandOptions : public Options {
1385   public:
1386     CommandOptions() : Options() { OptionParsingStarting(nullptr); }
1387 
1388     ~CommandOptions() override = default;
1389 
1390     void OptionParsingStarting(ExecutionContext *execution_context) override {
1391       m_json_thread = false;
1392       m_json_stopinfo = false;
1393     }
1394 
1395     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1396                           ExecutionContext *execution_context) override {
1397       const int short_option = m_getopt_table[option_idx].val;
1398       Status error;
1399 
1400       switch (short_option) {
1401       case 'j':
1402         m_json_thread = true;
1403         break;
1404 
1405       case 's':
1406         m_json_stopinfo = true;
1407         break;
1408 
1409       default:
1410         llvm_unreachable("Unimplemented option");
1411       }
1412       return error;
1413     }
1414 
1415     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
1416       return llvm::makeArrayRef(g_thread_info_options);
1417     }
1418 
1419     bool m_json_thread;
1420     bool m_json_stopinfo;
1421   };
1422 
1423   CommandObjectThreadInfo(CommandInterpreter &interpreter)
1424       : CommandObjectIterateOverThreads(
1425             interpreter, "thread info", "Show an extended summary of one or "
1426                                         "more threads.  Defaults to the "
1427                                         "current thread.",
1428             "thread info",
1429             eCommandRequiresProcess | eCommandTryTargetAPILock |
1430                 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused),
1431         m_options() {
1432     m_add_return = false;
1433   }
1434 
1435   ~CommandObjectThreadInfo() override = default;
1436 
1437   Options *GetOptions() override { return &m_options; }
1438 
1439   bool HandleOneThread(lldb::tid_t tid, CommandReturnObject &result) override {
1440     ThreadSP thread_sp =
1441         m_exe_ctx.GetProcessPtr()->GetThreadList().FindThreadByID(tid);
1442     if (!thread_sp) {
1443       result.AppendErrorWithFormat("thread no longer exists: 0x%" PRIx64 "\n",
1444                                    tid);
1445       result.SetStatus(eReturnStatusFailed);
1446       return false;
1447     }
1448 
1449     Thread *thread = thread_sp.get();
1450 
1451     Stream &strm = result.GetOutputStream();
1452     if (!thread->GetDescription(strm, eDescriptionLevelFull,
1453                                 m_options.m_json_thread,
1454                                 m_options.m_json_stopinfo)) {
1455       result.AppendErrorWithFormat("error displaying info for thread: \"%d\"\n",
1456                                    thread->GetIndexID());
1457       result.SetStatus(eReturnStatusFailed);
1458       return false;
1459     }
1460     return true;
1461   }
1462 
1463   CommandOptions m_options;
1464 };
1465 
1466 // CommandObjectThreadException
1467 
1468 class CommandObjectThreadException : public CommandObjectIterateOverThreads {
1469  public:
1470   CommandObjectThreadException(CommandInterpreter &interpreter)
1471       : CommandObjectIterateOverThreads(
1472             interpreter, "thread exception",
1473             "Display the current exception object for a thread. Defaults to "
1474             "the current thread.",
1475             "thread exception",
1476             eCommandRequiresProcess | eCommandTryTargetAPILock |
1477                 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused) {}
1478 
1479   ~CommandObjectThreadException() override = default;
1480 
1481   bool HandleOneThread(lldb::tid_t tid, CommandReturnObject &result) override {
1482     ThreadSP thread_sp =
1483         m_exe_ctx.GetProcessPtr()->GetThreadList().FindThreadByID(tid);
1484     if (!thread_sp) {
1485       result.AppendErrorWithFormat("thread no longer exists: 0x%" PRIx64 "\n",
1486                                    tid);
1487       result.SetStatus(eReturnStatusFailed);
1488       return false;
1489     }
1490 
1491     Stream &strm = result.GetOutputStream();
1492     ValueObjectSP exception_object_sp = thread_sp->GetCurrentException();
1493     if (exception_object_sp) {
1494       exception_object_sp->Dump(strm);
1495     }
1496 
1497     ThreadSP exception_thread_sp = thread_sp->GetCurrentExceptionBacktrace();
1498     if (exception_thread_sp && exception_thread_sp->IsValid()) {
1499       const uint32_t num_frames_with_source = 0;
1500       const bool stop_format = false;
1501       exception_thread_sp->GetStatus(strm, 0, UINT32_MAX,
1502                                      num_frames_with_source, stop_format);
1503     }
1504 
1505     return true;
1506   }
1507 };
1508 
1509 // CommandObjectThreadReturn
1510 #define LLDB_OPTIONS_thread_return
1511 #include "CommandOptions.inc"
1512 
1513 class CommandObjectThreadReturn : public CommandObjectRaw {
1514 public:
1515   class CommandOptions : public Options {
1516   public:
1517     CommandOptions() : Options(), m_from_expression(false) {
1518       // Keep default values of all options in one place: OptionParsingStarting
1519       // ()
1520       OptionParsingStarting(nullptr);
1521     }
1522 
1523     ~CommandOptions() override = default;
1524 
1525     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1526                           ExecutionContext *execution_context) override {
1527       Status error;
1528       const int short_option = m_getopt_table[option_idx].val;
1529 
1530       switch (short_option) {
1531       case 'x': {
1532         bool success;
1533         bool tmp_value =
1534             OptionArgParser::ToBoolean(option_arg, false, &success);
1535         if (success)
1536           m_from_expression = tmp_value;
1537         else {
1538           error.SetErrorStringWithFormat(
1539               "invalid boolean value '%s' for 'x' option",
1540               option_arg.str().c_str());
1541         }
1542       } break;
1543       default:
1544         llvm_unreachable("Unimplemented option");
1545       }
1546       return error;
1547     }
1548 
1549     void OptionParsingStarting(ExecutionContext *execution_context) override {
1550       m_from_expression = false;
1551     }
1552 
1553     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
1554       return llvm::makeArrayRef(g_thread_return_options);
1555     }
1556 
1557     bool m_from_expression;
1558 
1559     // Instance variables to hold the values for command options.
1560   };
1561 
1562   CommandObjectThreadReturn(CommandInterpreter &interpreter)
1563       : CommandObjectRaw(interpreter, "thread return",
1564                          "Prematurely return from a stack frame, "
1565                          "short-circuiting execution of newer frames "
1566                          "and optionally yielding a specified value.  Defaults "
1567                          "to the exiting the current stack "
1568                          "frame.",
1569                          "thread return",
1570                          eCommandRequiresFrame | eCommandTryTargetAPILock |
1571                              eCommandProcessMustBeLaunched |
1572                              eCommandProcessMustBePaused),
1573         m_options() {
1574     CommandArgumentEntry arg;
1575     CommandArgumentData expression_arg;
1576 
1577     // Define the first (and only) variant of this arg.
1578     expression_arg.arg_type = eArgTypeExpression;
1579     expression_arg.arg_repetition = eArgRepeatOptional;
1580 
1581     // There is only one variant this argument could be; put it into the
1582     // argument entry.
1583     arg.push_back(expression_arg);
1584 
1585     // Push the data for the first argument into the m_arguments vector.
1586     m_arguments.push_back(arg);
1587   }
1588 
1589   ~CommandObjectThreadReturn() override = default;
1590 
1591   Options *GetOptions() override { return &m_options; }
1592 
1593 protected:
1594   bool DoExecute(llvm::StringRef command,
1595                  CommandReturnObject &result) override {
1596     // I am going to handle this by hand, because I don't want you to have to
1597     // say:
1598     // "thread return -- -5".
1599     if (command.startswith("-x")) {
1600       if (command.size() != 2U)
1601         result.AppendWarning("Return values ignored when returning from user "
1602                              "called expressions");
1603 
1604       Thread *thread = m_exe_ctx.GetThreadPtr();
1605       Status error;
1606       error = thread->UnwindInnermostExpression();
1607       if (!error.Success()) {
1608         result.AppendErrorWithFormat("Unwinding expression failed - %s.",
1609                                      error.AsCString());
1610         result.SetStatus(eReturnStatusFailed);
1611       } else {
1612         bool success =
1613             thread->SetSelectedFrameByIndexNoisily(0, result.GetOutputStream());
1614         if (success) {
1615           m_exe_ctx.SetFrameSP(thread->GetSelectedFrame());
1616           result.SetStatus(eReturnStatusSuccessFinishResult);
1617         } else {
1618           result.AppendErrorWithFormat(
1619               "Could not select 0th frame after unwinding expression.");
1620           result.SetStatus(eReturnStatusFailed);
1621         }
1622       }
1623       return result.Succeeded();
1624     }
1625 
1626     ValueObjectSP return_valobj_sp;
1627 
1628     StackFrameSP frame_sp = m_exe_ctx.GetFrameSP();
1629     uint32_t frame_idx = frame_sp->GetFrameIndex();
1630 
1631     if (frame_sp->IsInlined()) {
1632       result.AppendError("Don't know how to return from inlined frames.");
1633       result.SetStatus(eReturnStatusFailed);
1634       return false;
1635     }
1636 
1637     if (!command.empty()) {
1638       Target *target = m_exe_ctx.GetTargetPtr();
1639       EvaluateExpressionOptions options;
1640 
1641       options.SetUnwindOnError(true);
1642       options.SetUseDynamic(eNoDynamicValues);
1643 
1644       ExpressionResults exe_results = eExpressionSetupError;
1645       exe_results = target->EvaluateExpression(command, frame_sp.get(),
1646                                                return_valobj_sp, options);
1647       if (exe_results != eExpressionCompleted) {
1648         if (return_valobj_sp)
1649           result.AppendErrorWithFormat(
1650               "Error evaluating result expression: %s",
1651               return_valobj_sp->GetError().AsCString());
1652         else
1653           result.AppendErrorWithFormat(
1654               "Unknown error evaluating result expression.");
1655         result.SetStatus(eReturnStatusFailed);
1656         return false;
1657       }
1658     }
1659 
1660     Status error;
1661     ThreadSP thread_sp = m_exe_ctx.GetThreadSP();
1662     const bool broadcast = true;
1663     error = thread_sp->ReturnFromFrame(frame_sp, return_valobj_sp, broadcast);
1664     if (!error.Success()) {
1665       result.AppendErrorWithFormat(
1666           "Error returning from frame %d of thread %d: %s.", frame_idx,
1667           thread_sp->GetIndexID(), error.AsCString());
1668       result.SetStatus(eReturnStatusFailed);
1669       return false;
1670     }
1671 
1672     result.SetStatus(eReturnStatusSuccessFinishResult);
1673     return true;
1674   }
1675 
1676   CommandOptions m_options;
1677 };
1678 
1679 // CommandObjectThreadJump
1680 #define LLDB_OPTIONS_thread_jump
1681 #include "CommandOptions.inc"
1682 
1683 class CommandObjectThreadJump : public CommandObjectParsed {
1684 public:
1685   class CommandOptions : public Options {
1686   public:
1687     CommandOptions() : Options() { OptionParsingStarting(nullptr); }
1688 
1689     ~CommandOptions() override = default;
1690 
1691     void OptionParsingStarting(ExecutionContext *execution_context) override {
1692       m_filenames.Clear();
1693       m_line_num = 0;
1694       m_line_offset = 0;
1695       m_load_addr = LLDB_INVALID_ADDRESS;
1696       m_force = false;
1697     }
1698 
1699     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1700                           ExecutionContext *execution_context) override {
1701       const int short_option = m_getopt_table[option_idx].val;
1702       Status error;
1703 
1704       switch (short_option) {
1705       case 'f':
1706         m_filenames.AppendIfUnique(FileSpec(option_arg));
1707         if (m_filenames.GetSize() > 1)
1708           return Status("only one source file expected.");
1709         break;
1710       case 'l':
1711         if (option_arg.getAsInteger(0, m_line_num))
1712           return Status("invalid line number: '%s'.", option_arg.str().c_str());
1713         break;
1714       case 'b':
1715         if (option_arg.getAsInteger(0, m_line_offset))
1716           return Status("invalid line offset: '%s'.", option_arg.str().c_str());
1717         break;
1718       case 'a':
1719         m_load_addr = OptionArgParser::ToAddress(execution_context, option_arg,
1720                                                  LLDB_INVALID_ADDRESS, &error);
1721         break;
1722       case 'r':
1723         m_force = true;
1724         break;
1725       default:
1726         llvm_unreachable("Unimplemented option");
1727       }
1728       return error;
1729     }
1730 
1731     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
1732       return llvm::makeArrayRef(g_thread_jump_options);
1733     }
1734 
1735     FileSpecList m_filenames;
1736     uint32_t m_line_num;
1737     int32_t m_line_offset;
1738     lldb::addr_t m_load_addr;
1739     bool m_force;
1740   };
1741 
1742   CommandObjectThreadJump(CommandInterpreter &interpreter)
1743       : CommandObjectParsed(
1744             interpreter, "thread jump",
1745             "Sets the program counter to a new address.", "thread jump",
1746             eCommandRequiresFrame | eCommandTryTargetAPILock |
1747                 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused),
1748         m_options() {}
1749 
1750   ~CommandObjectThreadJump() override = default;
1751 
1752   Options *GetOptions() override { return &m_options; }
1753 
1754 protected:
1755   bool DoExecute(Args &args, CommandReturnObject &result) override {
1756     RegisterContext *reg_ctx = m_exe_ctx.GetRegisterContext();
1757     StackFrame *frame = m_exe_ctx.GetFramePtr();
1758     Thread *thread = m_exe_ctx.GetThreadPtr();
1759     Target *target = m_exe_ctx.GetTargetPtr();
1760     const SymbolContext &sym_ctx =
1761         frame->GetSymbolContext(eSymbolContextLineEntry);
1762 
1763     if (m_options.m_load_addr != LLDB_INVALID_ADDRESS) {
1764       // Use this address directly.
1765       Address dest = Address(m_options.m_load_addr);
1766 
1767       lldb::addr_t callAddr = dest.GetCallableLoadAddress(target);
1768       if (callAddr == LLDB_INVALID_ADDRESS) {
1769         result.AppendErrorWithFormat("Invalid destination address.");
1770         result.SetStatus(eReturnStatusFailed);
1771         return false;
1772       }
1773 
1774       if (!reg_ctx->SetPC(callAddr)) {
1775         result.AppendErrorWithFormat("Error changing PC value for thread %d.",
1776                                      thread->GetIndexID());
1777         result.SetStatus(eReturnStatusFailed);
1778         return false;
1779       }
1780     } else {
1781       // Pick either the absolute line, or work out a relative one.
1782       int32_t line = (int32_t)m_options.m_line_num;
1783       if (line == 0)
1784         line = sym_ctx.line_entry.line + m_options.m_line_offset;
1785 
1786       // Try the current file, but override if asked.
1787       FileSpec file = sym_ctx.line_entry.file;
1788       if (m_options.m_filenames.GetSize() == 1)
1789         file = m_options.m_filenames.GetFileSpecAtIndex(0);
1790 
1791       if (!file) {
1792         result.AppendErrorWithFormat(
1793             "No source file available for the current location.");
1794         result.SetStatus(eReturnStatusFailed);
1795         return false;
1796       }
1797 
1798       std::string warnings;
1799       Status err = thread->JumpToLine(file, line, m_options.m_force, &warnings);
1800 
1801       if (err.Fail()) {
1802         result.SetError(err);
1803         return false;
1804       }
1805 
1806       if (!warnings.empty())
1807         result.AppendWarning(warnings.c_str());
1808     }
1809 
1810     result.SetStatus(eReturnStatusSuccessFinishResult);
1811     return true;
1812   }
1813 
1814   CommandOptions m_options;
1815 };
1816 
1817 // Next are the subcommands of CommandObjectMultiwordThreadPlan
1818 
1819 // CommandObjectThreadPlanList
1820 #define LLDB_OPTIONS_thread_plan_list
1821 #include "CommandOptions.inc"
1822 
1823 class CommandObjectThreadPlanList : public CommandObjectIterateOverThreads {
1824 public:
1825   class CommandOptions : public Options {
1826   public:
1827     CommandOptions() : Options() {
1828       // Keep default values of all options in one place: OptionParsingStarting
1829       // ()
1830       OptionParsingStarting(nullptr);
1831     }
1832 
1833     ~CommandOptions() override = default;
1834 
1835     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1836                           ExecutionContext *execution_context) override {
1837       Status error;
1838       const int short_option = m_getopt_table[option_idx].val;
1839 
1840       switch (short_option) {
1841       case 'i':
1842         m_internal = true;
1843         break;
1844       case 'v':
1845         m_verbose = true;
1846         break;
1847       default:
1848         llvm_unreachable("Unimplemented option");
1849       }
1850       return error;
1851     }
1852 
1853     void OptionParsingStarting(ExecutionContext *execution_context) override {
1854       m_verbose = false;
1855       m_internal = false;
1856     }
1857 
1858     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
1859       return llvm::makeArrayRef(g_thread_plan_list_options);
1860     }
1861 
1862     // Instance variables to hold the values for command options.
1863     bool m_verbose;
1864     bool m_internal;
1865   };
1866 
1867   CommandObjectThreadPlanList(CommandInterpreter &interpreter)
1868       : CommandObjectIterateOverThreads(
1869             interpreter, "thread plan list",
1870             "Show thread plans for one or more threads.  If no threads are "
1871             "specified, show the "
1872             "current thread.  Use the thread-index \"all\" to see all threads.",
1873             nullptr,
1874             eCommandRequiresProcess | eCommandRequiresThread |
1875                 eCommandTryTargetAPILock | eCommandProcessMustBeLaunched |
1876                 eCommandProcessMustBePaused),
1877         m_options() {}
1878 
1879   ~CommandObjectThreadPlanList() override = default;
1880 
1881   Options *GetOptions() override { return &m_options; }
1882 
1883 protected:
1884   bool HandleOneThread(lldb::tid_t tid, CommandReturnObject &result) override {
1885     ThreadSP thread_sp =
1886         m_exe_ctx.GetProcessPtr()->GetThreadList().FindThreadByID(tid);
1887     if (!thread_sp) {
1888       result.AppendErrorWithFormat("thread no longer exists: 0x%" PRIx64 "\n",
1889                                    tid);
1890       result.SetStatus(eReturnStatusFailed);
1891       return false;
1892     }
1893 
1894     Thread *thread = thread_sp.get();
1895 
1896     Stream &strm = result.GetOutputStream();
1897     DescriptionLevel desc_level = eDescriptionLevelFull;
1898     if (m_options.m_verbose)
1899       desc_level = eDescriptionLevelVerbose;
1900 
1901     thread->DumpThreadPlans(&strm, desc_level, m_options.m_internal, true);
1902     return true;
1903   }
1904 
1905   CommandOptions m_options;
1906 };
1907 
1908 class CommandObjectThreadPlanDiscard : public CommandObjectParsed {
1909 public:
1910   CommandObjectThreadPlanDiscard(CommandInterpreter &interpreter)
1911       : CommandObjectParsed(interpreter, "thread plan discard",
1912                             "Discards thread plans up to and including the "
1913                             "specified index (see 'thread plan list'.)  "
1914                             "Only user visible plans can be discarded.",
1915                             nullptr,
1916                             eCommandRequiresProcess | eCommandRequiresThread |
1917                                 eCommandTryTargetAPILock |
1918                                 eCommandProcessMustBeLaunched |
1919                                 eCommandProcessMustBePaused) {
1920     CommandArgumentEntry arg;
1921     CommandArgumentData plan_index_arg;
1922 
1923     // Define the first (and only) variant of this arg.
1924     plan_index_arg.arg_type = eArgTypeUnsignedInteger;
1925     plan_index_arg.arg_repetition = eArgRepeatPlain;
1926 
1927     // There is only one variant this argument could be; put it into the
1928     // argument entry.
1929     arg.push_back(plan_index_arg);
1930 
1931     // Push the data for the first argument into the m_arguments vector.
1932     m_arguments.push_back(arg);
1933   }
1934 
1935   ~CommandObjectThreadPlanDiscard() override = default;
1936 
1937   bool DoExecute(Args &args, CommandReturnObject &result) override {
1938     Thread *thread = m_exe_ctx.GetThreadPtr();
1939     if (args.GetArgumentCount() != 1) {
1940       result.AppendErrorWithFormat("Too many arguments, expected one - the "
1941                                    "thread plan index - but got %zu.",
1942                                    args.GetArgumentCount());
1943       result.SetStatus(eReturnStatusFailed);
1944       return false;
1945     }
1946 
1947     bool success;
1948     uint32_t thread_plan_idx =
1949         StringConvert::ToUInt32(args.GetArgumentAtIndex(0), 0, 0, &success);
1950     if (!success) {
1951       result.AppendErrorWithFormat(
1952           "Invalid thread index: \"%s\" - should be unsigned int.",
1953           args.GetArgumentAtIndex(0));
1954       result.SetStatus(eReturnStatusFailed);
1955       return false;
1956     }
1957 
1958     if (thread_plan_idx == 0) {
1959       result.AppendErrorWithFormat(
1960           "You wouldn't really want me to discard the base thread plan.");
1961       result.SetStatus(eReturnStatusFailed);
1962       return false;
1963     }
1964 
1965     if (thread->DiscardUserThreadPlansUpToIndex(thread_plan_idx)) {
1966       result.SetStatus(eReturnStatusSuccessFinishNoResult);
1967       return true;
1968     } else {
1969       result.AppendErrorWithFormat(
1970           "Could not find User thread plan with index %s.",
1971           args.GetArgumentAtIndex(0));
1972       result.SetStatus(eReturnStatusFailed);
1973       return false;
1974     }
1975   }
1976 };
1977 
1978 // CommandObjectMultiwordThreadPlan
1979 
1980 class CommandObjectMultiwordThreadPlan : public CommandObjectMultiword {
1981 public:
1982   CommandObjectMultiwordThreadPlan(CommandInterpreter &interpreter)
1983       : CommandObjectMultiword(
1984             interpreter, "plan",
1985             "Commands for managing thread plans that control execution.",
1986             "thread plan <subcommand> [<subcommand objects]") {
1987     LoadSubCommand(
1988         "list", CommandObjectSP(new CommandObjectThreadPlanList(interpreter)));
1989     LoadSubCommand(
1990         "discard",
1991         CommandObjectSP(new CommandObjectThreadPlanDiscard(interpreter)));
1992   }
1993 
1994   ~CommandObjectMultiwordThreadPlan() override = default;
1995 };
1996 
1997 // CommandObjectMultiwordThread
1998 
1999 CommandObjectMultiwordThread::CommandObjectMultiwordThread(
2000     CommandInterpreter &interpreter)
2001     : CommandObjectMultiword(interpreter, "thread", "Commands for operating on "
2002                                                     "one or more threads in "
2003                                                     "the current process.",
2004                              "thread <subcommand> [<subcommand-options>]") {
2005   LoadSubCommand("backtrace", CommandObjectSP(new CommandObjectThreadBacktrace(
2006                                   interpreter)));
2007   LoadSubCommand("continue",
2008                  CommandObjectSP(new CommandObjectThreadContinue(interpreter)));
2009   LoadSubCommand("list",
2010                  CommandObjectSP(new CommandObjectThreadList(interpreter)));
2011   LoadSubCommand("return",
2012                  CommandObjectSP(new CommandObjectThreadReturn(interpreter)));
2013   LoadSubCommand("jump",
2014                  CommandObjectSP(new CommandObjectThreadJump(interpreter)));
2015   LoadSubCommand("select",
2016                  CommandObjectSP(new CommandObjectThreadSelect(interpreter)));
2017   LoadSubCommand("until",
2018                  CommandObjectSP(new CommandObjectThreadUntil(interpreter)));
2019   LoadSubCommand("info",
2020                  CommandObjectSP(new CommandObjectThreadInfo(interpreter)));
2021   LoadSubCommand(
2022       "exception",
2023       CommandObjectSP(new CommandObjectThreadException(interpreter)));
2024   LoadSubCommand("step-in",
2025                  CommandObjectSP(new CommandObjectThreadStepWithTypeAndScope(
2026                      interpreter, "thread step-in",
2027                      "Source level single step, stepping into calls.  Defaults "
2028                      "to current thread unless specified.",
2029                      nullptr, eStepTypeInto, eStepScopeSource)));
2030 
2031   LoadSubCommand("step-out",
2032                  CommandObjectSP(new CommandObjectThreadStepWithTypeAndScope(
2033                      interpreter, "thread step-out",
2034                      "Finish executing the current stack frame and stop after "
2035                      "returning.  Defaults to current thread unless specified.",
2036                      nullptr, eStepTypeOut, eStepScopeSource)));
2037 
2038   LoadSubCommand("step-over",
2039                  CommandObjectSP(new CommandObjectThreadStepWithTypeAndScope(
2040                      interpreter, "thread step-over",
2041                      "Source level single step, stepping over calls.  Defaults "
2042                      "to current thread unless specified.",
2043                      nullptr, eStepTypeOver, eStepScopeSource)));
2044 
2045   LoadSubCommand("step-inst",
2046                  CommandObjectSP(new CommandObjectThreadStepWithTypeAndScope(
2047                      interpreter, "thread step-inst",
2048                      "Instruction level single step, stepping into calls.  "
2049                      "Defaults to current thread unless specified.",
2050                      nullptr, eStepTypeTrace, eStepScopeInstruction)));
2051 
2052   LoadSubCommand("step-inst-over",
2053                  CommandObjectSP(new CommandObjectThreadStepWithTypeAndScope(
2054                      interpreter, "thread step-inst-over",
2055                      "Instruction level single step, stepping over calls.  "
2056                      "Defaults to current thread unless specified.",
2057                      nullptr, eStepTypeTraceOver, eStepScopeInstruction)));
2058 
2059   LoadSubCommand(
2060       "step-scripted",
2061       CommandObjectSP(new CommandObjectThreadStepWithTypeAndScope(
2062           interpreter, "thread step-scripted",
2063           "Step as instructed by the script class passed in the -C option.",
2064           nullptr, eStepTypeScripted, eStepScopeSource)));
2065 
2066   LoadSubCommand("plan", CommandObjectSP(new CommandObjectMultiwordThreadPlan(
2067                              interpreter)));
2068 }
2069 
2070 CommandObjectMultiwordThread::~CommandObjectMultiwordThread() = default;
2071