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