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