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