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