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