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