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