1 //===-- CommandObjectThread.cpp ---------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "CommandObjectThread.h"
14 // Other libraries and framework includes
16 #include "lldb/Core/SourceManager.h"
17 #include "lldb/Core/State.h"
18 #include "lldb/Core/ValueObject.h"
19 #include "lldb/Host/Host.h"
20 #include "lldb/Host/StringConvert.h"
21 #include "lldb/Interpreter/CommandInterpreter.h"
22 #include "lldb/Interpreter/CommandReturnObject.h"
23 #include "lldb/Interpreter/Options.h"
24 #include "lldb/Symbol/CompileUnit.h"
25 #include "lldb/Symbol/Function.h"
26 #include "lldb/Symbol/LineEntry.h"
27 #include "lldb/Symbol/LineTable.h"
28 #include "lldb/Target/Process.h"
29 #include "lldb/Target/RegisterContext.h"
30 #include "lldb/Target/SystemRuntime.h"
31 #include "lldb/Target/Target.h"
32 #include "lldb/Target/Thread.h"
33 #include "lldb/Target/ThreadPlan.h"
34 #include "lldb/Target/ThreadPlanStepInRange.h"
35 #include "lldb/Target/ThreadPlanStepInstruction.h"
36 #include "lldb/Target/ThreadPlanStepOut.h"
37 #include "lldb/Target/ThreadPlanStepRange.h"
38 #include "lldb/lldb-private.h"
41 using namespace lldb_private;
43 //-------------------------------------------------------------------------
44 // CommandObjectThreadBacktrace
45 //-------------------------------------------------------------------------
47 class CommandObjectIterateOverThreads : public CommandObjectParsed {
49 CommandObjectIterateOverThreads(CommandInterpreter &interpreter,
50 const char *name, const char *help,
51 const char *syntax, uint32_t flags)
52 : CommandObjectParsed(interpreter, name, help, syntax, flags) {}
54 ~CommandObjectIterateOverThreads() override = default;
56 bool DoExecute(Args &command, CommandReturnObject &result) override {
57 result.SetStatus(m_success_return);
59 if (command.GetArgumentCount() == 0) {
60 Thread *thread = m_exe_ctx.GetThreadPtr();
61 if (!HandleOneThread(thread->GetID(), result))
63 return result.Succeeded();
66 // Use tids instead of ThreadSPs to prevent deadlocking problems which
67 // result from JIT-ing
68 // code while iterating over the (locked) ThreadSP list.
69 std::vector<lldb::tid_t> tids;
71 if (command.GetArgumentCount() == 1 &&
72 ::strcmp(command.GetArgumentAtIndex(0), "all") == 0) {
73 Process *process = m_exe_ctx.GetProcessPtr();
75 for (ThreadSP thread_sp : process->Threads())
76 tids.push_back(thread_sp->GetID());
78 const size_t num_args = command.GetArgumentCount();
79 Process *process = m_exe_ctx.GetProcessPtr();
81 std::lock_guard<std::recursive_mutex> guard(
82 process->GetThreadList().GetMutex());
84 for (size_t i = 0; i < num_args; i++) {
87 uint32_t thread_idx = StringConvert::ToUInt32(
88 command.GetArgumentAtIndex(i), 0, 0, &success);
90 result.AppendErrorWithFormat("invalid thread specification: \"%s\"\n",
91 command.GetArgumentAtIndex(i));
92 result.SetStatus(eReturnStatusFailed);
97 process->GetThreadList().FindThreadByIndexID(thread_idx);
100 result.AppendErrorWithFormat("no thread with index: \"%s\"\n",
101 command.GetArgumentAtIndex(i));
102 result.SetStatus(eReturnStatusFailed);
106 tids.push_back(thread->GetID());
111 for (const lldb::tid_t &tid : tids) {
112 if (idx != 0 && m_add_return)
113 result.AppendMessage("");
115 if (!HandleOneThread(tid, result))
120 return result.Succeeded();
124 // Override this to do whatever you need to do for one thread.
126 // If you return false, the iteration will stop, otherwise it will proceed.
127 // The result is set to m_success_return (defaults to
128 // eReturnStatusSuccessFinishResult) before the iteration,
129 // so you only need to set the return status in HandleOneThread if you want to
130 // indicate an error.
131 // If m_add_return is true, a blank line will be inserted between each of the
132 // listings (except the last one.)
134 virtual bool HandleOneThread(lldb::tid_t, CommandReturnObject &result) = 0;
136 ReturnStatus m_success_return = eReturnStatusSuccessFinishResult;
137 bool m_add_return = true;
140 //-------------------------------------------------------------------------
141 // CommandObjectThreadBacktrace
142 //-------------------------------------------------------------------------
144 static OptionDefinition g_thread_backtrace_options[] = {
146 { LLDB_OPT_SET_1, false, "count", 'c', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeCount, "How many frames to display (-1 for all)" },
147 { LLDB_OPT_SET_1, false, "start", 's', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeFrameIndex, "Frame in which to start the backtrace" },
148 { LLDB_OPT_SET_1, false, "extended", 'e', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBoolean, "Show the extended backtrace, if available" }
152 class CommandObjectThreadBacktrace : public CommandObjectIterateOverThreads {
154 class CommandOptions : public Options {
156 CommandOptions() : Options() {
157 // Keep default values of all options in one place: OptionParsingStarting
159 OptionParsingStarting(nullptr);
162 ~CommandOptions() override = default;
164 Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
165 ExecutionContext *execution_context) override {
167 const int short_option = m_getopt_table[option_idx].val;
169 switch (short_option) {
171 int32_t input_count = 0;
172 if (option_arg.getAsInteger(0, m_count)) {
173 m_count = UINT32_MAX;
174 error.SetErrorStringWithFormat(
175 "invalid integer value for option '%c'", short_option);
176 } else if (input_count < 0)
177 m_count = UINT32_MAX;
180 if (option_arg.getAsInteger(0, m_start))
181 error.SetErrorStringWithFormat(
182 "invalid integer value for option '%c'", short_option);
186 m_extended_backtrace =
187 Args::StringToBoolean(option_arg, false, &success);
189 error.SetErrorStringWithFormat(
190 "invalid boolean value for option '%c'", short_option);
193 error.SetErrorStringWithFormat("invalid short option character '%c'",
200 void OptionParsingStarting(ExecutionContext *execution_context) override {
201 m_count = UINT32_MAX;
203 m_extended_backtrace = false;
206 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
207 return llvm::makeArrayRef(g_thread_backtrace_options);
210 // Instance variables to hold the values for command options.
213 bool m_extended_backtrace;
216 CommandObjectThreadBacktrace(CommandInterpreter &interpreter)
217 : CommandObjectIterateOverThreads(
218 interpreter, "thread backtrace",
219 "Show thread call stacks. Defaults to the current thread, thread "
220 "indexes can be specified as arguments. Use the thread-index "
222 "to see all threads.",
224 eCommandRequiresProcess | eCommandRequiresThread |
225 eCommandTryTargetAPILock | eCommandProcessMustBeLaunched |
226 eCommandProcessMustBePaused),
229 ~CommandObjectThreadBacktrace() override = default;
231 Options *GetOptions() override { return &m_options; }
234 void DoExtendedBacktrace(Thread *thread, CommandReturnObject &result) {
235 SystemRuntime *runtime = thread->GetProcess()->GetSystemRuntime();
237 Stream &strm = result.GetOutputStream();
238 const std::vector<ConstString> &types =
239 runtime->GetExtendedBacktraceTypes();
240 for (auto type : types) {
241 ThreadSP ext_thread_sp = runtime->GetExtendedBacktraceThread(
242 thread->shared_from_this(), type);
243 if (ext_thread_sp && ext_thread_sp->IsValid()) {
244 const uint32_t num_frames_with_source = 0;
245 const bool stop_format = false;
246 if (ext_thread_sp->GetStatus(strm, m_options.m_start,
248 num_frames_with_source,
250 DoExtendedBacktrace(ext_thread_sp.get(), result);
257 bool HandleOneThread(lldb::tid_t tid, CommandReturnObject &result) override {
259 m_exe_ctx.GetProcessPtr()->GetThreadList().FindThreadByID(tid);
261 result.AppendErrorWithFormat(
262 "thread disappeared while computing backtraces: 0x%" PRIx64 "\n",
264 result.SetStatus(eReturnStatusFailed);
268 Thread *thread = thread_sp.get();
270 Stream &strm = result.GetOutputStream();
272 // Don't show source context when doing backtraces.
273 const uint32_t num_frames_with_source = 0;
274 const bool stop_format = true;
275 if (!thread->GetStatus(strm, m_options.m_start, m_options.m_count,
276 num_frames_with_source, stop_format)) {
277 result.AppendErrorWithFormat(
278 "error displaying backtrace for thread: \"0x%4.4x\"\n",
279 thread->GetIndexID());
280 result.SetStatus(eReturnStatusFailed);
283 if (m_options.m_extended_backtrace) {
284 DoExtendedBacktrace(thread, result);
290 CommandOptions m_options;
293 enum StepScope { eStepScopeSource, eStepScopeInstruction };
295 static OptionEnumValueElement g_tri_running_mode[] = {
296 {eOnlyThisThread, "this-thread", "Run only this thread"},
297 {eAllThreads, "all-threads", "Run all threads"},
298 {eOnlyDuringStepping, "while-stepping",
299 "Run only this thread while stepping"},
300 {0, nullptr, nullptr}};
302 static OptionEnumValueElement g_duo_running_mode[] = {
303 {eOnlyThisThread, "this-thread", "Run only this thread"},
304 {eAllThreads, "all-threads", "Run all threads"},
305 {0, nullptr, nullptr}};
307 static OptionDefinition g_thread_step_scope_options[] = {
309 { LLDB_OPT_SET_1, false, "step-in-avoids-no-debug", 'a', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBoolean, "A boolean value that sets whether stepping into functions will step over functions with no debug information." },
310 { LLDB_OPT_SET_1, false, "step-out-avoids-no-debug", 'A', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBoolean, "A boolean value, if true stepping out of functions will continue to step out till it hits a function with debug information." },
311 { LLDB_OPT_SET_1, false, "count", 'c', OptionParser::eRequiredArgument, nullptr, nullptr, 1, eArgTypeCount, "How many times to perform the stepping operation - currently only supported for step-inst and next-inst." },
312 { LLDB_OPT_SET_1, false, "end-linenumber", 'e', OptionParser::eRequiredArgument, nullptr, nullptr, 1, eArgTypeLineNum, "The line at which to stop stepping - defaults to the next line and only supported for step-in and step-over. You can also pass the string 'block' to step to the end of the current block. This is particularly useful in conjunction with --step-target to step through a complex calling sequence." },
313 { LLDB_OPT_SET_1, false, "run-mode", 'm', OptionParser::eRequiredArgument, nullptr, g_tri_running_mode, 0, eArgTypeRunMode, "Determine how to run other threads while stepping the current thread." },
314 { LLDB_OPT_SET_1, false, "step-over-regexp", 'r', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeRegularExpression, "A regular expression that defines function names to not to stop at when stepping in." },
315 { LLDB_OPT_SET_1, false, "step-in-target", 't', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeFunctionName, "The name of the directly called function step in should stop at when stepping into." },
316 { LLDB_OPT_SET_2, false, "python-class", 'C', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypePythonClass, "The name of the class that will manage this step - only supported for Scripted Step." }
320 class CommandObjectThreadStepWithTypeAndScope : public CommandObjectParsed {
322 class CommandOptions : public Options {
324 CommandOptions() : Options() {
325 // Keep default values of all options in one place: OptionParsingStarting
327 OptionParsingStarting(nullptr);
330 ~CommandOptions() override = default;
332 Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
333 ExecutionContext *execution_context) override {
335 const int short_option = m_getopt_table[option_idx].val;
337 switch (short_option) {
340 bool avoid_no_debug = Args::StringToBoolean(option_arg, true, &success);
342 error.SetErrorStringWithFormat(
343 "invalid boolean value for option '%c'", short_option);
345 m_step_in_avoid_no_debug =
346 avoid_no_debug ? eLazyBoolYes : eLazyBoolNo;
352 bool avoid_no_debug = Args::StringToBoolean(option_arg, true, &success);
354 error.SetErrorStringWithFormat(
355 "invalid boolean value for option '%c'", short_option);
357 m_step_out_avoid_no_debug =
358 avoid_no_debug ? eLazyBoolYes : eLazyBoolNo;
363 if (option_arg.getAsInteger(0, m_step_count))
364 error.SetErrorStringWithFormat("invalid step count '%s'",
365 option_arg.str().c_str());
369 m_class_name.clear();
370 m_class_name.assign(option_arg);
374 OptionEnumValueElement *enum_values =
375 GetDefinitions()[option_idx].enum_values;
376 m_run_mode = (lldb::RunMode)Args::StringToOptionEnum(
377 option_arg, enum_values, eOnlyDuringStepping, error);
381 if (option_arg == "block") {
382 m_end_line_is_block_end = 1;
385 if (option_arg.getAsInteger(0, m_end_line))
386 error.SetErrorStringWithFormat("invalid end line number '%s'",
387 option_arg.str().c_str());
391 m_avoid_regexp.clear();
392 m_avoid_regexp.assign(option_arg);
396 m_step_in_target.clear();
397 m_step_in_target.assign(option_arg);
401 error.SetErrorStringWithFormat("invalid short option character '%c'",
408 void OptionParsingStarting(ExecutionContext *execution_context) override {
409 m_step_in_avoid_no_debug = eLazyBoolCalculate;
410 m_step_out_avoid_no_debug = eLazyBoolCalculate;
411 m_run_mode = eOnlyDuringStepping;
413 // Check if we are in Non-Stop mode
415 execution_context ? execution_context->GetTargetSP() : TargetSP();
416 if (target_sp && target_sp->GetNonStopModeEnabled())
417 m_run_mode = eOnlyThisThread;
419 m_avoid_regexp.clear();
420 m_step_in_target.clear();
421 m_class_name.clear();
423 m_end_line = LLDB_INVALID_LINE_NUMBER;
424 m_end_line_is_block_end = false;
427 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
428 return llvm::makeArrayRef(g_thread_step_scope_options);
431 // Instance variables to hold the values for command options.
432 LazyBool m_step_in_avoid_no_debug;
433 LazyBool m_step_out_avoid_no_debug;
435 std::string m_avoid_regexp;
436 std::string m_step_in_target;
437 std::string m_class_name;
438 uint32_t m_step_count;
440 bool m_end_line_is_block_end;
443 CommandObjectThreadStepWithTypeAndScope(CommandInterpreter &interpreter,
444 const char *name, const char *help,
447 StepScope step_scope)
448 : CommandObjectParsed(interpreter, name, help, syntax,
449 eCommandRequiresProcess | eCommandRequiresThread |
450 eCommandTryTargetAPILock |
451 eCommandProcessMustBeLaunched |
452 eCommandProcessMustBePaused),
453 m_step_type(step_type), m_step_scope(step_scope), m_options() {
454 CommandArgumentEntry arg;
455 CommandArgumentData thread_id_arg;
457 // Define the first (and only) variant of this arg.
458 thread_id_arg.arg_type = eArgTypeThreadID;
459 thread_id_arg.arg_repetition = eArgRepeatOptional;
461 // There is only one variant this argument could be; put it into the
463 arg.push_back(thread_id_arg);
465 // Push the data for the first argument into the m_arguments vector.
466 m_arguments.push_back(arg);
469 ~CommandObjectThreadStepWithTypeAndScope() override = default;
471 Options *GetOptions() override { return &m_options; }
474 bool DoExecute(Args &command, CommandReturnObject &result) override {
475 Process *process = m_exe_ctx.GetProcessPtr();
476 bool synchronous_execution = m_interpreter.GetSynchronous();
478 const uint32_t num_threads = process->GetThreadList().GetSize();
479 Thread *thread = nullptr;
481 if (command.GetArgumentCount() == 0) {
482 thread = GetDefaultThread();
484 if (thread == nullptr) {
485 result.AppendError("no selected thread in process");
486 result.SetStatus(eReturnStatusFailed);
490 const char *thread_idx_cstr = command.GetArgumentAtIndex(0);
491 uint32_t step_thread_idx =
492 StringConvert::ToUInt32(thread_idx_cstr, LLDB_INVALID_INDEX32);
493 if (step_thread_idx == LLDB_INVALID_INDEX32) {
494 result.AppendErrorWithFormat("invalid thread index '%s'.\n",
496 result.SetStatus(eReturnStatusFailed);
500 process->GetThreadList().FindThreadByIndexID(step_thread_idx).get();
501 if (thread == nullptr) {
502 result.AppendErrorWithFormat(
503 "Thread index %u is out of range (valid values are 0 - %u).\n",
504 step_thread_idx, num_threads);
505 result.SetStatus(eReturnStatusFailed);
510 if (m_step_type == eStepTypeScripted) {
511 if (m_options.m_class_name.empty()) {
512 result.AppendErrorWithFormat("empty class name for scripted step.");
513 result.SetStatus(eReturnStatusFailed);
515 } else if (!m_interpreter.GetScriptInterpreter()->CheckObjectExists(
516 m_options.m_class_name.c_str())) {
517 result.AppendErrorWithFormat(
518 "class for scripted step: \"%s\" does not exist.",
519 m_options.m_class_name.c_str());
520 result.SetStatus(eReturnStatusFailed);
525 if (m_options.m_end_line != LLDB_INVALID_LINE_NUMBER &&
526 m_step_type != eStepTypeInto) {
527 result.AppendErrorWithFormat(
528 "end line option is only valid for step into");
529 result.SetStatus(eReturnStatusFailed);
533 const bool abort_other_plans = false;
534 const lldb::RunMode stop_other_threads = m_options.m_run_mode;
536 // This is a bit unfortunate, but not all the commands in this command
538 // only while stepping, so I use the bool for them.
539 bool bool_stop_other_threads;
540 if (m_options.m_run_mode == eAllThreads)
541 bool_stop_other_threads = false;
542 else if (m_options.m_run_mode == eOnlyDuringStepping)
543 bool_stop_other_threads =
544 (m_step_type != eStepTypeOut && m_step_type != eStepTypeScripted);
546 bool_stop_other_threads = true;
548 ThreadPlanSP new_plan_sp;
550 if (m_step_type == eStepTypeInto) {
551 StackFrame *frame = thread->GetStackFrameAtIndex(0).get();
552 assert(frame != nullptr);
554 if (frame->HasDebugInformation()) {
556 SymbolContext sc = frame->GetSymbolContext(eSymbolContextEverything);
557 if (m_options.m_end_line != LLDB_INVALID_LINE_NUMBER) {
559 if (!sc.GetAddressRangeFromHereToEndLine(m_options.m_end_line, range,
561 result.AppendErrorWithFormat("invalid end-line option: %s.",
563 result.SetStatus(eReturnStatusFailed);
566 } else if (m_options.m_end_line_is_block_end) {
568 Block *block = frame->GetSymbolContext(eSymbolContextBlock).block;
570 result.AppendErrorWithFormat("Could not find the current block.");
571 result.SetStatus(eReturnStatusFailed);
575 AddressRange block_range;
576 Address pc_address = frame->GetFrameCodeAddress();
577 block->GetRangeContainingAddress(pc_address, block_range);
578 if (!block_range.GetBaseAddress().IsValid()) {
579 result.AppendErrorWithFormat(
580 "Could not find the current block address.");
581 result.SetStatus(eReturnStatusFailed);
584 lldb::addr_t pc_offset_in_block =
585 pc_address.GetFileAddress() -
586 block_range.GetBaseAddress().GetFileAddress();
587 lldb::addr_t range_length =
588 block_range.GetByteSize() - pc_offset_in_block;
589 range = AddressRange(pc_address, range_length);
591 range = sc.line_entry.range;
594 new_plan_sp = thread->QueueThreadPlanForStepInRange(
595 abort_other_plans, range,
596 frame->GetSymbolContext(eSymbolContextEverything),
597 m_options.m_step_in_target.c_str(), stop_other_threads,
598 m_options.m_step_in_avoid_no_debug,
599 m_options.m_step_out_avoid_no_debug);
601 if (new_plan_sp && !m_options.m_avoid_regexp.empty()) {
602 ThreadPlanStepInRange *step_in_range_plan =
603 static_cast<ThreadPlanStepInRange *>(new_plan_sp.get());
604 step_in_range_plan->SetAvoidRegexp(m_options.m_avoid_regexp.c_str());
607 new_plan_sp = thread->QueueThreadPlanForStepSingleInstruction(
608 false, abort_other_plans, bool_stop_other_threads);
609 } else if (m_step_type == eStepTypeOver) {
610 StackFrame *frame = thread->GetStackFrameAtIndex(0).get();
612 if (frame->HasDebugInformation())
613 new_plan_sp = thread->QueueThreadPlanForStepOverRange(
615 frame->GetSymbolContext(eSymbolContextEverything).line_entry,
616 frame->GetSymbolContext(eSymbolContextEverything),
617 stop_other_threads, m_options.m_step_out_avoid_no_debug);
619 new_plan_sp = thread->QueueThreadPlanForStepSingleInstruction(
620 true, abort_other_plans, bool_stop_other_threads);
621 } else if (m_step_type == eStepTypeTrace) {
622 new_plan_sp = thread->QueueThreadPlanForStepSingleInstruction(
623 false, abort_other_plans, bool_stop_other_threads);
624 } else if (m_step_type == eStepTypeTraceOver) {
625 new_plan_sp = thread->QueueThreadPlanForStepSingleInstruction(
626 true, abort_other_plans, bool_stop_other_threads);
627 } else if (m_step_type == eStepTypeOut) {
628 new_plan_sp = thread->QueueThreadPlanForStepOut(
629 abort_other_plans, nullptr, false, bool_stop_other_threads, eVoteYes,
630 eVoteNoOpinion, thread->GetSelectedFrameIndex(),
631 m_options.m_step_out_avoid_no_debug);
632 } else if (m_step_type == eStepTypeScripted) {
633 new_plan_sp = thread->QueueThreadPlanForStepScripted(
634 abort_other_plans, m_options.m_class_name.c_str(),
635 bool_stop_other_threads);
637 result.AppendError("step type is not supported");
638 result.SetStatus(eReturnStatusFailed);
642 // If we got a new plan, then set it to be a master plan (User level Plans
643 // should be master plans
644 // so that they can be interruptible). Then resume the process.
647 new_plan_sp->SetIsMasterPlan(true);
648 new_plan_sp->SetOkayToDiscard(false);
650 if (m_options.m_step_count > 1) {
651 if (new_plan_sp->SetIterationCount(m_options.m_step_count)) {
652 result.AppendWarning(
653 "step operation does not support iteration count.");
657 process->GetThreadList().SetSelectedThreadByID(thread->GetID());
659 const uint32_t iohandler_id = process->GetIOHandlerID();
663 if (synchronous_execution)
664 error = process->ResumeSynchronous(&stream);
666 error = process->Resume();
668 // There is a race condition where this thread will return up the call
669 // stack to the main command handler
670 // and show an (lldb) prompt before HandlePrivateEvent (from
671 // PrivateStateThread) has
672 // a chance to call PushProcessIOHandler().
673 process->SyncIOHandler(iohandler_id, 2000);
675 if (synchronous_execution) {
676 // If any state changed events had anything to say, add that to the
678 if (stream.GetSize() > 0)
679 result.AppendMessage(stream.GetString());
681 process->GetThreadList().SetSelectedThreadByID(thread->GetID());
682 result.SetDidChangeProcessState(true);
683 result.SetStatus(eReturnStatusSuccessFinishNoResult);
685 result.SetStatus(eReturnStatusSuccessContinuingNoResult);
688 result.AppendError("Couldn't find thread plan to implement step type.");
689 result.SetStatus(eReturnStatusFailed);
691 return result.Succeeded();
695 StepType m_step_type;
696 StepScope m_step_scope;
697 CommandOptions m_options;
700 //-------------------------------------------------------------------------
701 // CommandObjectThreadContinue
702 //-------------------------------------------------------------------------
704 class CommandObjectThreadContinue : public CommandObjectParsed {
706 CommandObjectThreadContinue(CommandInterpreter &interpreter)
707 : CommandObjectParsed(
708 interpreter, "thread continue",
709 "Continue execution of the current target process. One "
710 "or more threads may be specified, by default all "
713 eCommandRequiresThread | eCommandTryTargetAPILock |
714 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused) {
715 CommandArgumentEntry arg;
716 CommandArgumentData thread_idx_arg;
718 // Define the first (and only) variant of this arg.
719 thread_idx_arg.arg_type = eArgTypeThreadIndex;
720 thread_idx_arg.arg_repetition = eArgRepeatPlus;
722 // There is only one variant this argument could be; put it into the
724 arg.push_back(thread_idx_arg);
726 // Push the data for the first argument into the m_arguments vector.
727 m_arguments.push_back(arg);
730 ~CommandObjectThreadContinue() override = default;
732 bool DoExecute(Args &command, CommandReturnObject &result) override {
733 bool synchronous_execution = m_interpreter.GetSynchronous();
735 if (!m_interpreter.GetDebugger().GetSelectedTarget()) {
736 result.AppendError("invalid target, create a debug target using the "
737 "'target create' command");
738 result.SetStatus(eReturnStatusFailed);
742 Process *process = m_exe_ctx.GetProcessPtr();
743 if (process == nullptr) {
744 result.AppendError("no process exists. Cannot continue");
745 result.SetStatus(eReturnStatusFailed);
749 StateType state = process->GetState();
750 if ((state == eStateCrashed) || (state == eStateStopped) ||
751 (state == eStateSuspended)) {
752 const size_t argc = command.GetArgumentCount();
754 // These two lines appear at the beginning of both blocks in
755 // this if..else, but that is because we need to release the
756 // lock before calling process->Resume below.
757 std::lock_guard<std::recursive_mutex> guard(
758 process->GetThreadList().GetMutex());
759 const uint32_t num_threads = process->GetThreadList().GetSize();
760 std::vector<Thread *> resume_threads;
761 for (auto &entry : command.entries()) {
763 if (entry.ref.getAsInteger(0, thread_idx)) {
764 result.AppendErrorWithFormat(
765 "invalid thread index argument: \"%s\".\n", entry.c_str());
766 result.SetStatus(eReturnStatusFailed);
770 process->GetThreadList().FindThreadByIndexID(thread_idx).get();
773 resume_threads.push_back(thread);
775 result.AppendErrorWithFormat("invalid thread index %u.\n",
777 result.SetStatus(eReturnStatusFailed);
782 if (resume_threads.empty()) {
783 result.AppendError("no valid thread indexes were specified");
784 result.SetStatus(eReturnStatusFailed);
787 if (resume_threads.size() == 1)
788 result.AppendMessageWithFormat("Resuming thread: ");
790 result.AppendMessageWithFormat("Resuming threads: ");
792 for (uint32_t idx = 0; idx < num_threads; ++idx) {
794 process->GetThreadList().GetThreadAtIndex(idx).get();
795 std::vector<Thread *>::iterator this_thread_pos =
796 find(resume_threads.begin(), resume_threads.end(), thread);
798 if (this_thread_pos != resume_threads.end()) {
799 resume_threads.erase(this_thread_pos);
800 if (!resume_threads.empty())
801 result.AppendMessageWithFormat("%u, ", thread->GetIndexID());
803 result.AppendMessageWithFormat("%u ", thread->GetIndexID());
805 const bool override_suspend = true;
806 thread->SetResumeState(eStateRunning, override_suspend);
808 thread->SetResumeState(eStateSuspended);
811 result.AppendMessageWithFormat("in process %" PRIu64 "\n",
815 // These two lines appear at the beginning of both blocks in
816 // this if..else, but that is because we need to release the
817 // lock before calling process->Resume below.
818 std::lock_guard<std::recursive_mutex> guard(
819 process->GetThreadList().GetMutex());
820 const uint32_t num_threads = process->GetThreadList().GetSize();
821 Thread *current_thread = GetDefaultThread();
822 if (current_thread == nullptr) {
823 result.AppendError("the process doesn't have a current thread");
824 result.SetStatus(eReturnStatusFailed);
827 // Set the actions that the threads should each take when resuming
828 for (uint32_t idx = 0; idx < num_threads; ++idx) {
829 Thread *thread = process->GetThreadList().GetThreadAtIndex(idx).get();
830 if (thread == current_thread) {
831 result.AppendMessageWithFormat("Resuming thread 0x%4.4" PRIx64
832 " in process %" PRIu64 "\n",
833 thread->GetID(), process->GetID());
834 const bool override_suspend = true;
835 thread->SetResumeState(eStateRunning, override_suspend);
837 thread->SetResumeState(eStateSuspended);
844 if (synchronous_execution)
845 error = process->ResumeSynchronous(&stream);
847 error = process->Resume();
849 // We should not be holding the thread list lock when we do this.
850 if (error.Success()) {
851 result.AppendMessageWithFormat("Process %" PRIu64 " resuming\n",
853 if (synchronous_execution) {
854 // If any state changed events had anything to say, add that to the
856 if (stream.GetSize() > 0)
857 result.AppendMessage(stream.GetString());
859 result.SetDidChangeProcessState(true);
860 result.SetStatus(eReturnStatusSuccessFinishNoResult);
862 result.SetStatus(eReturnStatusSuccessContinuingNoResult);
865 result.AppendErrorWithFormat("Failed to resume process: %s\n",
867 result.SetStatus(eReturnStatusFailed);
870 result.AppendErrorWithFormat(
871 "Process cannot be continued from its current state (%s).\n",
872 StateAsCString(state));
873 result.SetStatus(eReturnStatusFailed);
876 return result.Succeeded();
880 //-------------------------------------------------------------------------
881 // CommandObjectThreadUntil
882 //-------------------------------------------------------------------------
884 static OptionDefinition g_thread_until_options[] = {
886 { LLDB_OPT_SET_1, false, "frame", 'f', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeFrameIndex, "Frame index for until operation - defaults to 0" },
887 { LLDB_OPT_SET_1, false, "thread", 't', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeThreadIndex, "Thread index for the thread for until operation" },
888 { LLDB_OPT_SET_1, false, "run-mode",'m', OptionParser::eRequiredArgument, nullptr, g_duo_running_mode, 0, eArgTypeRunMode, "Determine how to run other threads while stepping this one" },
889 { LLDB_OPT_SET_1, false, "address", 'a', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeAddressOrExpression, "Run until we reach the specified address, or leave the function - can be specified multiple times." }
893 class CommandObjectThreadUntil : public CommandObjectParsed {
895 class CommandOptions : public Options {
897 uint32_t m_thread_idx;
898 uint32_t m_frame_idx;
901 : Options(), m_thread_idx(LLDB_INVALID_THREAD_ID),
902 m_frame_idx(LLDB_INVALID_FRAME_ID) {
903 // Keep default values of all options in one place: OptionParsingStarting
905 OptionParsingStarting(nullptr);
908 ~CommandOptions() override = default;
910 Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
911 ExecutionContext *execution_context) override {
913 const int short_option = m_getopt_table[option_idx].val;
915 switch (short_option) {
917 lldb::addr_t tmp_addr = Args::StringToAddress(
918 execution_context, option_arg, LLDB_INVALID_ADDRESS, &error);
920 m_until_addrs.push_back(tmp_addr);
923 if (option_arg.getAsInteger(0, m_thread_idx)) {
924 m_thread_idx = LLDB_INVALID_INDEX32;
925 error.SetErrorStringWithFormat("invalid thread index '%s'",
926 option_arg.str().c_str());
930 if (option_arg.getAsInteger(0, m_frame_idx)) {
931 m_frame_idx = LLDB_INVALID_FRAME_ID;
932 error.SetErrorStringWithFormat("invalid frame index '%s'",
933 option_arg.str().c_str());
937 OptionEnumValueElement *enum_values =
938 GetDefinitions()[option_idx].enum_values;
939 lldb::RunMode run_mode = (lldb::RunMode)Args::StringToOptionEnum(
940 option_arg, enum_values, eOnlyDuringStepping, error);
942 if (error.Success()) {
943 if (run_mode == eAllThreads)
944 m_stop_others = false;
946 m_stop_others = true;
950 error.SetErrorStringWithFormat("invalid short option character '%c'",
957 void OptionParsingStarting(ExecutionContext *execution_context) override {
958 m_thread_idx = LLDB_INVALID_THREAD_ID;
960 m_stop_others = false;
961 m_until_addrs.clear();
964 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
965 return llvm::makeArrayRef(g_thread_until_options);
968 uint32_t m_step_thread_idx;
970 std::vector<lldb::addr_t> m_until_addrs;
972 // Instance variables to hold the values for command options.
975 CommandObjectThreadUntil(CommandInterpreter &interpreter)
976 : CommandObjectParsed(
977 interpreter, "thread until",
978 "Continue until a line number or address is reached by the "
979 "current or specified thread. Stops when returning from "
980 "the current function as a safety measure. "
981 "The target line number(s) are given as arguments, and if more than one"
982 " is provided, stepping will stop when the first one is hit.",
984 eCommandRequiresThread | eCommandTryTargetAPILock |
985 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused),
987 CommandArgumentEntry arg;
988 CommandArgumentData line_num_arg;
990 // Define the first (and only) variant of this arg.
991 line_num_arg.arg_type = eArgTypeLineNum;
992 line_num_arg.arg_repetition = eArgRepeatPlain;
994 // There is only one variant this argument could be; put it into the
996 arg.push_back(line_num_arg);
998 // Push the data for the first argument into the m_arguments vector.
999 m_arguments.push_back(arg);
1002 ~CommandObjectThreadUntil() override = default;
1004 Options *GetOptions() override { return &m_options; }
1007 bool DoExecute(Args &command, CommandReturnObject &result) override {
1008 bool synchronous_execution = m_interpreter.GetSynchronous();
1010 Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
1011 if (target == nullptr) {
1012 result.AppendError("invalid target, create a debug target using the "
1013 "'target create' command");
1014 result.SetStatus(eReturnStatusFailed);
1018 Process *process = m_exe_ctx.GetProcessPtr();
1019 if (process == nullptr) {
1020 result.AppendError("need a valid process to step");
1021 result.SetStatus(eReturnStatusFailed);
1023 Thread *thread = nullptr;
1024 std::vector<uint32_t> line_numbers;
1026 if (command.GetArgumentCount() >= 1) {
1027 size_t num_args = command.GetArgumentCount();
1028 for (size_t i = 0; i < num_args; i++) {
1029 uint32_t line_number;
1030 line_number = StringConvert::ToUInt32(command.GetArgumentAtIndex(i),
1032 if (line_number == UINT32_MAX) {
1033 result.AppendErrorWithFormat("invalid line number: '%s'.\n",
1034 command.GetArgumentAtIndex(i));
1035 result.SetStatus(eReturnStatusFailed);
1038 line_numbers.push_back(line_number);
1040 } else if (m_options.m_until_addrs.empty()) {
1041 result.AppendErrorWithFormat("No line number or address provided:\n%s",
1042 GetSyntax().str().c_str());
1043 result.SetStatus(eReturnStatusFailed);
1047 if (m_options.m_thread_idx == LLDB_INVALID_THREAD_ID) {
1048 thread = GetDefaultThread();
1050 thread = process->GetThreadList()
1051 .FindThreadByIndexID(m_options.m_thread_idx)
1055 if (thread == nullptr) {
1056 const uint32_t num_threads = process->GetThreadList().GetSize();
1057 result.AppendErrorWithFormat(
1058 "Thread index %u is out of range (valid values are 0 - %u).\n",
1059 m_options.m_thread_idx, num_threads);
1060 result.SetStatus(eReturnStatusFailed);
1064 const bool abort_other_plans = false;
1067 thread->GetStackFrameAtIndex(m_options.m_frame_idx).get();
1068 if (frame == nullptr) {
1069 result.AppendErrorWithFormat(
1070 "Frame index %u is out of range for thread %u.\n",
1071 m_options.m_frame_idx, m_options.m_thread_idx);
1072 result.SetStatus(eReturnStatusFailed);
1076 ThreadPlanSP new_plan_sp;
1078 if (frame->HasDebugInformation()) {
1079 // Finally we got here... Translate the given line number to a bunch of
1081 SymbolContext sc(frame->GetSymbolContext(eSymbolContextCompUnit));
1082 LineTable *line_table = nullptr;
1084 line_table = sc.comp_unit->GetLineTable();
1086 if (line_table == nullptr) {
1087 result.AppendErrorWithFormat("Failed to resolve the line table for "
1088 "frame %u of thread index %u.\n",
1089 m_options.m_frame_idx,
1090 m_options.m_thread_idx);
1091 result.SetStatus(eReturnStatusFailed);
1095 LineEntry function_start;
1096 uint32_t index_ptr = 0, end_ptr;
1097 std::vector<addr_t> address_list;
1099 // Find the beginning & end index of the
1100 AddressRange fun_addr_range = sc.function->GetAddressRange();
1101 Address fun_start_addr = fun_addr_range.GetBaseAddress();
1102 line_table->FindLineEntryByAddress(fun_start_addr, function_start,
1105 Address fun_end_addr(fun_start_addr.GetSection(),
1106 fun_start_addr.GetOffset() +
1107 fun_addr_range.GetByteSize());
1109 bool all_in_function = true;
1111 line_table->FindLineEntryByAddress(fun_end_addr, function_start,
1114 for (uint32_t line_number : line_numbers) {
1115 uint32_t start_idx_ptr = index_ptr;
1116 while (start_idx_ptr <= end_ptr) {
1117 LineEntry line_entry;
1118 const bool exact = false;
1119 start_idx_ptr = sc.comp_unit->FindLineEntry(
1120 start_idx_ptr, line_number, sc.comp_unit, exact, &line_entry);
1121 if (start_idx_ptr == UINT32_MAX)
1125 line_entry.range.GetBaseAddress().GetLoadAddress(target);
1126 if (address != LLDB_INVALID_ADDRESS) {
1127 if (fun_addr_range.ContainsLoadAddress(address, target))
1128 address_list.push_back(address);
1130 all_in_function = false;
1136 for (lldb::addr_t address : m_options.m_until_addrs) {
1137 if (fun_addr_range.ContainsLoadAddress(address, target))
1138 address_list.push_back(address);
1140 all_in_function = false;
1143 if (address_list.empty()) {
1144 if (all_in_function)
1145 result.AppendErrorWithFormat(
1146 "No line entries matching until target.\n");
1148 result.AppendErrorWithFormat(
1149 "Until target outside of the current function.\n");
1151 result.SetStatus(eReturnStatusFailed);
1155 new_plan_sp = thread->QueueThreadPlanForStepUntil(
1156 abort_other_plans, &address_list.front(), address_list.size(),
1157 m_options.m_stop_others, m_options.m_frame_idx);
1158 // User level plans should be master plans so they can be interrupted
1159 // (e.g. by hitting a breakpoint)
1160 // and other plans executed by the user (stepping around the breakpoint)
1161 // and then a "continue"
1162 // will resume the original plan.
1163 new_plan_sp->SetIsMasterPlan(true);
1164 new_plan_sp->SetOkayToDiscard(false);
1166 result.AppendErrorWithFormat(
1167 "Frame index %u of thread %u has no debug information.\n",
1168 m_options.m_frame_idx, m_options.m_thread_idx);
1169 result.SetStatus(eReturnStatusFailed);
1173 process->GetThreadList().SetSelectedThreadByID(m_options.m_thread_idx);
1175 StreamString stream;
1177 if (synchronous_execution)
1178 error = process->ResumeSynchronous(&stream);
1180 error = process->Resume();
1182 if (error.Success()) {
1183 result.AppendMessageWithFormat("Process %" PRIu64 " resuming\n",
1185 if (synchronous_execution) {
1186 // If any state changed events had anything to say, add that to the
1188 if (stream.GetSize() > 0)
1189 result.AppendMessage(stream.GetString());
1191 result.SetDidChangeProcessState(true);
1192 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1194 result.SetStatus(eReturnStatusSuccessContinuingNoResult);
1197 result.AppendErrorWithFormat("Failed to resume process: %s.\n",
1199 result.SetStatus(eReturnStatusFailed);
1202 return result.Succeeded();
1205 CommandOptions m_options;
1208 //-------------------------------------------------------------------------
1209 // CommandObjectThreadSelect
1210 //-------------------------------------------------------------------------
1212 class CommandObjectThreadSelect : public CommandObjectParsed {
1214 CommandObjectThreadSelect(CommandInterpreter &interpreter)
1215 : CommandObjectParsed(interpreter, "thread select",
1216 "Change the currently selected thread.", nullptr,
1217 eCommandRequiresProcess | eCommandTryTargetAPILock |
1218 eCommandProcessMustBeLaunched |
1219 eCommandProcessMustBePaused) {
1220 CommandArgumentEntry arg;
1221 CommandArgumentData thread_idx_arg;
1223 // Define the first (and only) variant of this arg.
1224 thread_idx_arg.arg_type = eArgTypeThreadIndex;
1225 thread_idx_arg.arg_repetition = eArgRepeatPlain;
1227 // There is only one variant this argument could be; put it into the
1229 arg.push_back(thread_idx_arg);
1231 // Push the data for the first argument into the m_arguments vector.
1232 m_arguments.push_back(arg);
1235 ~CommandObjectThreadSelect() override = default;
1238 bool DoExecute(Args &command, CommandReturnObject &result) override {
1239 Process *process = m_exe_ctx.GetProcessPtr();
1240 if (process == nullptr) {
1241 result.AppendError("no process");
1242 result.SetStatus(eReturnStatusFailed);
1244 } else if (command.GetArgumentCount() != 1) {
1245 result.AppendErrorWithFormat(
1246 "'%s' takes exactly one thread index argument:\nUsage: %s\n",
1247 m_cmd_name.c_str(), m_cmd_syntax.c_str());
1248 result.SetStatus(eReturnStatusFailed);
1253 StringConvert::ToUInt32(command.GetArgumentAtIndex(0), 0, 0);
1255 Thread *new_thread =
1256 process->GetThreadList().FindThreadByIndexID(index_id).get();
1257 if (new_thread == nullptr) {
1258 result.AppendErrorWithFormat("invalid thread #%s.\n",
1259 command.GetArgumentAtIndex(0));
1260 result.SetStatus(eReturnStatusFailed);
1264 process->GetThreadList().SetSelectedThreadByID(new_thread->GetID(), true);
1265 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1267 return result.Succeeded();
1271 //-------------------------------------------------------------------------
1272 // CommandObjectThreadList
1273 //-------------------------------------------------------------------------
1275 class CommandObjectThreadList : public CommandObjectParsed {
1277 CommandObjectThreadList(CommandInterpreter &interpreter)
1278 : CommandObjectParsed(
1279 interpreter, "thread list",
1280 "Show a summary of each thread in the current target process.",
1282 eCommandRequiresProcess | eCommandTryTargetAPILock |
1283 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused) {}
1285 ~CommandObjectThreadList() override = default;
1288 bool DoExecute(Args &command, CommandReturnObject &result) override {
1289 Stream &strm = result.GetOutputStream();
1290 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1291 Process *process = m_exe_ctx.GetProcessPtr();
1292 const bool only_threads_with_stop_reason = false;
1293 const uint32_t start_frame = 0;
1294 const uint32_t num_frames = 0;
1295 const uint32_t num_frames_with_source = 0;
1296 process->GetStatus(strm);
1297 process->GetThreadStatus(strm, only_threads_with_stop_reason, start_frame,
1298 num_frames, num_frames_with_source, false);
1299 return result.Succeeded();
1303 //-------------------------------------------------------------------------
1304 // CommandObjectThreadInfo
1305 //-------------------------------------------------------------------------
1307 static OptionDefinition g_thread_info_options[] = {
1309 { LLDB_OPT_SET_ALL, false, "json", 'j', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Display the thread info in JSON format." },
1310 { LLDB_OPT_SET_ALL, false, "stop-info", 's', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Display the extended stop info in JSON format." }
1314 class CommandObjectThreadInfo : public CommandObjectIterateOverThreads {
1316 class CommandOptions : public Options {
1318 CommandOptions() : Options() { OptionParsingStarting(nullptr); }
1320 ~CommandOptions() override = default;
1322 void OptionParsingStarting(ExecutionContext *execution_context) override {
1323 m_json_thread = false;
1324 m_json_stopinfo = false;
1327 Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1328 ExecutionContext *execution_context) override {
1329 const int short_option = m_getopt_table[option_idx].val;
1332 switch (short_option) {
1334 m_json_thread = true;
1338 m_json_stopinfo = true;
1342 return Error("invalid short option character '%c'", short_option);
1347 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
1348 return llvm::makeArrayRef(g_thread_info_options);
1352 bool m_json_stopinfo;
1355 CommandObjectThreadInfo(CommandInterpreter &interpreter)
1356 : CommandObjectIterateOverThreads(
1357 interpreter, "thread info", "Show an extended summary of one or "
1358 "more threads. Defaults to the "
1361 eCommandRequiresProcess | eCommandTryTargetAPILock |
1362 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused),
1364 m_add_return = false;
1367 ~CommandObjectThreadInfo() override = default;
1369 Options *GetOptions() override { return &m_options; }
1371 bool HandleOneThread(lldb::tid_t tid, CommandReturnObject &result) override {
1372 ThreadSP thread_sp =
1373 m_exe_ctx.GetProcessPtr()->GetThreadList().FindThreadByID(tid);
1375 result.AppendErrorWithFormat("thread no longer exists: 0x%" PRIx64 "\n",
1377 result.SetStatus(eReturnStatusFailed);
1381 Thread *thread = thread_sp.get();
1383 Stream &strm = result.GetOutputStream();
1384 if (!thread->GetDescription(strm, eDescriptionLevelFull,
1385 m_options.m_json_thread,
1386 m_options.m_json_stopinfo)) {
1387 result.AppendErrorWithFormat("error displaying info for thread: \"%d\"\n",
1388 thread->GetIndexID());
1389 result.SetStatus(eReturnStatusFailed);
1395 CommandOptions m_options;
1398 //-------------------------------------------------------------------------
1399 // CommandObjectThreadReturn
1400 //-------------------------------------------------------------------------
1402 static OptionDefinition g_thread_return_options[] = {
1404 { LLDB_OPT_SET_ALL, false, "from-expression", 'x', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Return from the innermost expression evaluation." }
1408 class CommandObjectThreadReturn : public CommandObjectRaw {
1410 class CommandOptions : public Options {
1412 CommandOptions() : Options(), m_from_expression(false) {
1413 // Keep default values of all options in one place: OptionParsingStarting
1415 OptionParsingStarting(nullptr);
1418 ~CommandOptions() override = default;
1420 Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1421 ExecutionContext *execution_context) override {
1423 const int short_option = m_getopt_table[option_idx].val;
1425 switch (short_option) {
1428 bool tmp_value = Args::StringToBoolean(option_arg, false, &success);
1430 m_from_expression = tmp_value;
1432 error.SetErrorStringWithFormat(
1433 "invalid boolean value '%s' for 'x' option",
1434 option_arg.str().c_str());
1438 error.SetErrorStringWithFormat("invalid short option character '%c'",
1445 void OptionParsingStarting(ExecutionContext *execution_context) override {
1446 m_from_expression = false;
1449 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
1450 return llvm::makeArrayRef(g_thread_return_options);
1453 bool m_from_expression;
1455 // Instance variables to hold the values for command options.
1458 CommandObjectThreadReturn(CommandInterpreter &interpreter)
1459 : CommandObjectRaw(interpreter, "thread return",
1460 "Prematurely return from a stack frame, "
1461 "short-circuiting execution of newer frames "
1462 "and optionally yielding a specified value. Defaults "
1463 "to the exiting the current stack "
1466 eCommandRequiresFrame | eCommandTryTargetAPILock |
1467 eCommandProcessMustBeLaunched |
1468 eCommandProcessMustBePaused),
1470 CommandArgumentEntry arg;
1471 CommandArgumentData expression_arg;
1473 // Define the first (and only) variant of this arg.
1474 expression_arg.arg_type = eArgTypeExpression;
1475 expression_arg.arg_repetition = eArgRepeatOptional;
1477 // There is only one variant this argument could be; put it into the
1479 arg.push_back(expression_arg);
1481 // Push the data for the first argument into the m_arguments vector.
1482 m_arguments.push_back(arg);
1485 ~CommandObjectThreadReturn() override = default;
1487 Options *GetOptions() override { return &m_options; }
1490 bool DoExecute(const char *command, CommandReturnObject &result) override {
1491 // I am going to handle this by hand, because I don't want you to have to
1493 // "thread return -- -5".
1494 if (command[0] == '-' && command[1] == 'x') {
1495 if (command && command[2] != '\0')
1496 result.AppendWarning("Return values ignored when returning from user "
1497 "called expressions");
1499 Thread *thread = m_exe_ctx.GetThreadPtr();
1501 error = thread->UnwindInnermostExpression();
1502 if (!error.Success()) {
1503 result.AppendErrorWithFormat("Unwinding expression failed - %s.",
1505 result.SetStatus(eReturnStatusFailed);
1508 thread->SetSelectedFrameByIndexNoisily(0, result.GetOutputStream());
1510 m_exe_ctx.SetFrameSP(thread->GetSelectedFrame());
1511 result.SetStatus(eReturnStatusSuccessFinishResult);
1513 result.AppendErrorWithFormat(
1514 "Could not select 0th frame after unwinding expression.");
1515 result.SetStatus(eReturnStatusFailed);
1518 return result.Succeeded();
1521 ValueObjectSP return_valobj_sp;
1523 StackFrameSP frame_sp = m_exe_ctx.GetFrameSP();
1524 uint32_t frame_idx = frame_sp->GetFrameIndex();
1526 if (frame_sp->IsInlined()) {
1527 result.AppendError("Don't know how to return from inlined frames.");
1528 result.SetStatus(eReturnStatusFailed);
1532 if (command && command[0] != '\0') {
1533 Target *target = m_exe_ctx.GetTargetPtr();
1534 EvaluateExpressionOptions options;
1536 options.SetUnwindOnError(true);
1537 options.SetUseDynamic(eNoDynamicValues);
1539 ExpressionResults exe_results = eExpressionSetupError;
1540 exe_results = target->EvaluateExpression(command, frame_sp.get(),
1541 return_valobj_sp, options);
1542 if (exe_results != eExpressionCompleted) {
1543 if (return_valobj_sp)
1544 result.AppendErrorWithFormat(
1545 "Error evaluating result expression: %s",
1546 return_valobj_sp->GetError().AsCString());
1548 result.AppendErrorWithFormat(
1549 "Unknown error evaluating result expression.");
1550 result.SetStatus(eReturnStatusFailed);
1556 ThreadSP thread_sp = m_exe_ctx.GetThreadSP();
1557 const bool broadcast = true;
1558 error = thread_sp->ReturnFromFrame(frame_sp, return_valobj_sp, broadcast);
1559 if (!error.Success()) {
1560 result.AppendErrorWithFormat(
1561 "Error returning from frame %d of thread %d: %s.", frame_idx,
1562 thread_sp->GetIndexID(), error.AsCString());
1563 result.SetStatus(eReturnStatusFailed);
1567 result.SetStatus(eReturnStatusSuccessFinishResult);
1571 CommandOptions m_options;
1574 //-------------------------------------------------------------------------
1575 // CommandObjectThreadJump
1576 //-------------------------------------------------------------------------
1578 static OptionDefinition g_thread_jump_options[] = {
1580 { LLDB_OPT_SET_1, false, "file", 'f', OptionParser::eRequiredArgument, nullptr, nullptr, CommandCompletions::eSourceFileCompletion, eArgTypeFilename, "Specifies the source file to jump to." },
1581 { LLDB_OPT_SET_1, true, "line", 'l', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeLineNum, "Specifies the line number to jump to." },
1582 { LLDB_OPT_SET_2, true, "by", 'b', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeOffset, "Jumps by a relative line offset from the current line." },
1583 { LLDB_OPT_SET_3, true, "address", 'a', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeAddressOrExpression, "Jumps to a specific address." },
1584 { LLDB_OPT_SET_1 | LLDB_OPT_SET_2 | LLDB_OPT_SET_3, false, "force", 'r', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Allows the PC to leave the current function." }
1588 class CommandObjectThreadJump : public CommandObjectParsed {
1590 class CommandOptions : public Options {
1592 CommandOptions() : Options() { OptionParsingStarting(nullptr); }
1594 ~CommandOptions() override = default;
1596 void OptionParsingStarting(ExecutionContext *execution_context) override {
1597 m_filenames.Clear();
1600 m_load_addr = LLDB_INVALID_ADDRESS;
1604 Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1605 ExecutionContext *execution_context) override {
1606 const int short_option = m_getopt_table[option_idx].val;
1609 switch (short_option) {
1611 m_filenames.AppendIfUnique(FileSpec(option_arg, false));
1612 if (m_filenames.GetSize() > 1)
1613 return Error("only one source file expected.");
1616 if (option_arg.getAsInteger(0, m_line_num))
1617 return Error("invalid line number: '%s'.", option_arg.str().c_str());
1620 if (option_arg.getAsInteger(0, m_line_offset))
1621 return Error("invalid line offset: '%s'.", option_arg.str().c_str());
1624 m_load_addr = Args::StringToAddress(execution_context, option_arg,
1625 LLDB_INVALID_ADDRESS, &error);
1631 return Error("invalid short option character '%c'", short_option);
1636 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
1637 return llvm::makeArrayRef(g_thread_jump_options);
1640 FileSpecList m_filenames;
1641 uint32_t m_line_num;
1642 int32_t m_line_offset;
1643 lldb::addr_t m_load_addr;
1647 CommandObjectThreadJump(CommandInterpreter &interpreter)
1648 : CommandObjectParsed(
1649 interpreter, "thread jump",
1650 "Sets the program counter to a new address.", "thread jump",
1651 eCommandRequiresFrame | eCommandTryTargetAPILock |
1652 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused),
1655 ~CommandObjectThreadJump() override = default;
1657 Options *GetOptions() override { return &m_options; }
1660 bool DoExecute(Args &args, CommandReturnObject &result) override {
1661 RegisterContext *reg_ctx = m_exe_ctx.GetRegisterContext();
1662 StackFrame *frame = m_exe_ctx.GetFramePtr();
1663 Thread *thread = m_exe_ctx.GetThreadPtr();
1664 Target *target = m_exe_ctx.GetTargetPtr();
1665 const SymbolContext &sym_ctx =
1666 frame->GetSymbolContext(eSymbolContextLineEntry);
1668 if (m_options.m_load_addr != LLDB_INVALID_ADDRESS) {
1669 // Use this address directly.
1670 Address dest = Address(m_options.m_load_addr);
1672 lldb::addr_t callAddr = dest.GetCallableLoadAddress(target);
1673 if (callAddr == LLDB_INVALID_ADDRESS) {
1674 result.AppendErrorWithFormat("Invalid destination address.");
1675 result.SetStatus(eReturnStatusFailed);
1679 if (!reg_ctx->SetPC(callAddr)) {
1680 result.AppendErrorWithFormat("Error changing PC value for thread %d.",
1681 thread->GetIndexID());
1682 result.SetStatus(eReturnStatusFailed);
1686 // Pick either the absolute line, or work out a relative one.
1687 int32_t line = (int32_t)m_options.m_line_num;
1689 line = sym_ctx.line_entry.line + m_options.m_line_offset;
1691 // Try the current file, but override if asked.
1692 FileSpec file = sym_ctx.line_entry.file;
1693 if (m_options.m_filenames.GetSize() == 1)
1694 file = m_options.m_filenames.GetFileSpecAtIndex(0);
1697 result.AppendErrorWithFormat(
1698 "No source file available for the current location.");
1699 result.SetStatus(eReturnStatusFailed);
1703 std::string warnings;
1704 Error err = thread->JumpToLine(file, line, m_options.m_force, &warnings);
1707 result.SetError(err);
1711 if (!warnings.empty())
1712 result.AppendWarning(warnings.c_str());
1715 result.SetStatus(eReturnStatusSuccessFinishResult);
1719 CommandOptions m_options;
1722 //-------------------------------------------------------------------------
1723 // Next are the subcommands of CommandObjectMultiwordThreadPlan
1724 //-------------------------------------------------------------------------
1726 //-------------------------------------------------------------------------
1727 // CommandObjectThreadPlanList
1728 //-------------------------------------------------------------------------
1730 static OptionDefinition g_thread_plan_list_options[] = {
1732 { LLDB_OPT_SET_1, false, "verbose", 'v', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Display more information about the thread plans" },
1733 { LLDB_OPT_SET_1, false, "internal", 'i', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Display internal as well as user thread plans" }
1737 class CommandObjectThreadPlanList : public CommandObjectIterateOverThreads {
1739 class CommandOptions : public Options {
1741 CommandOptions() : Options() {
1742 // Keep default values of all options in one place: OptionParsingStarting
1744 OptionParsingStarting(nullptr);
1747 ~CommandOptions() override = default;
1749 Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1750 ExecutionContext *execution_context) override {
1752 const int short_option = m_getopt_table[option_idx].val;
1754 switch (short_option) {
1762 error.SetErrorStringWithFormat("invalid short option character '%c'",
1769 void OptionParsingStarting(ExecutionContext *execution_context) override {
1774 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
1775 return llvm::makeArrayRef(g_thread_plan_list_options);
1778 // Instance variables to hold the values for command options.
1783 CommandObjectThreadPlanList(CommandInterpreter &interpreter)
1784 : CommandObjectIterateOverThreads(
1785 interpreter, "thread plan list",
1786 "Show thread plans for one or more threads. If no threads are "
1787 "specified, show the "
1788 "current thread. Use the thread-index \"all\" to see all threads.",
1790 eCommandRequiresProcess | eCommandRequiresThread |
1791 eCommandTryTargetAPILock | eCommandProcessMustBeLaunched |
1792 eCommandProcessMustBePaused),
1795 ~CommandObjectThreadPlanList() override = default;
1797 Options *GetOptions() override { return &m_options; }
1800 bool HandleOneThread(lldb::tid_t tid, CommandReturnObject &result) override {
1801 ThreadSP thread_sp =
1802 m_exe_ctx.GetProcessPtr()->GetThreadList().FindThreadByID(tid);
1804 result.AppendErrorWithFormat("thread no longer exists: 0x%" PRIx64 "\n",
1806 result.SetStatus(eReturnStatusFailed);
1810 Thread *thread = thread_sp.get();
1812 Stream &strm = result.GetOutputStream();
1813 DescriptionLevel desc_level = eDescriptionLevelFull;
1814 if (m_options.m_verbose)
1815 desc_level = eDescriptionLevelVerbose;
1817 thread->DumpThreadPlans(&strm, desc_level, m_options.m_internal, true);
1821 CommandOptions m_options;
1824 class CommandObjectThreadPlanDiscard : public CommandObjectParsed {
1826 CommandObjectThreadPlanDiscard(CommandInterpreter &interpreter)
1827 : CommandObjectParsed(interpreter, "thread plan discard",
1828 "Discards thread plans up to and including the "
1829 "specified index (see 'thread plan list'.) "
1830 "Only user visible plans can be discarded.",
1832 eCommandRequiresProcess | eCommandRequiresThread |
1833 eCommandTryTargetAPILock |
1834 eCommandProcessMustBeLaunched |
1835 eCommandProcessMustBePaused) {
1836 CommandArgumentEntry arg;
1837 CommandArgumentData plan_index_arg;
1839 // Define the first (and only) variant of this arg.
1840 plan_index_arg.arg_type = eArgTypeUnsignedInteger;
1841 plan_index_arg.arg_repetition = eArgRepeatPlain;
1843 // There is only one variant this argument could be; put it into the
1845 arg.push_back(plan_index_arg);
1847 // Push the data for the first argument into the m_arguments vector.
1848 m_arguments.push_back(arg);
1851 ~CommandObjectThreadPlanDiscard() override = default;
1853 bool DoExecute(Args &args, CommandReturnObject &result) override {
1854 Thread *thread = m_exe_ctx.GetThreadPtr();
1855 if (args.GetArgumentCount() != 1) {
1856 result.AppendErrorWithFormat("Too many arguments, expected one - the "
1857 "thread plan index - but got %zu.",
1858 args.GetArgumentCount());
1859 result.SetStatus(eReturnStatusFailed);
1864 uint32_t thread_plan_idx =
1865 StringConvert::ToUInt32(args.GetArgumentAtIndex(0), 0, 0, &success);
1867 result.AppendErrorWithFormat(
1868 "Invalid thread index: \"%s\" - should be unsigned int.",
1869 args.GetArgumentAtIndex(0));
1870 result.SetStatus(eReturnStatusFailed);
1874 if (thread_plan_idx == 0) {
1875 result.AppendErrorWithFormat(
1876 "You wouldn't really want me to discard the base thread plan.");
1877 result.SetStatus(eReturnStatusFailed);
1881 if (thread->DiscardUserThreadPlansUpToIndex(thread_plan_idx)) {
1882 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1885 result.AppendErrorWithFormat(
1886 "Could not find User thread plan with index %s.",
1887 args.GetArgumentAtIndex(0));
1888 result.SetStatus(eReturnStatusFailed);
1894 //-------------------------------------------------------------------------
1895 // CommandObjectMultiwordThreadPlan
1896 //-------------------------------------------------------------------------
1898 class CommandObjectMultiwordThreadPlan : public CommandObjectMultiword {
1900 CommandObjectMultiwordThreadPlan(CommandInterpreter &interpreter)
1901 : CommandObjectMultiword(
1902 interpreter, "plan",
1903 "Commands for managing thread plans that control execution.",
1904 "thread plan <subcommand> [<subcommand objects]") {
1906 "list", CommandObjectSP(new CommandObjectThreadPlanList(interpreter)));
1909 CommandObjectSP(new CommandObjectThreadPlanDiscard(interpreter)));
1912 ~CommandObjectMultiwordThreadPlan() override = default;
1915 //-------------------------------------------------------------------------
1916 // CommandObjectMultiwordThread
1917 //-------------------------------------------------------------------------
1919 CommandObjectMultiwordThread::CommandObjectMultiwordThread(
1920 CommandInterpreter &interpreter)
1921 : CommandObjectMultiword(interpreter, "thread", "Commands for operating on "
1922 "one or more threads in "
1923 "the current process.",
1924 "thread <subcommand> [<subcommand-options>]") {
1925 LoadSubCommand("backtrace", CommandObjectSP(new CommandObjectThreadBacktrace(
1927 LoadSubCommand("continue",
1928 CommandObjectSP(new CommandObjectThreadContinue(interpreter)));
1929 LoadSubCommand("list",
1930 CommandObjectSP(new CommandObjectThreadList(interpreter)));
1931 LoadSubCommand("return",
1932 CommandObjectSP(new CommandObjectThreadReturn(interpreter)));
1933 LoadSubCommand("jump",
1934 CommandObjectSP(new CommandObjectThreadJump(interpreter)));
1935 LoadSubCommand("select",
1936 CommandObjectSP(new CommandObjectThreadSelect(interpreter)));
1937 LoadSubCommand("until",
1938 CommandObjectSP(new CommandObjectThreadUntil(interpreter)));
1939 LoadSubCommand("info",
1940 CommandObjectSP(new CommandObjectThreadInfo(interpreter)));
1941 LoadSubCommand("step-in",
1942 CommandObjectSP(new CommandObjectThreadStepWithTypeAndScope(
1943 interpreter, "thread step-in",
1944 "Source level single step, stepping into calls. Defaults "
1945 "to current thread unless specified.",
1946 nullptr, eStepTypeInto, eStepScopeSource)));
1948 LoadSubCommand("step-out",
1949 CommandObjectSP(new CommandObjectThreadStepWithTypeAndScope(
1950 interpreter, "thread step-out",
1951 "Finish executing the current stack frame and stop after "
1952 "returning. Defaults to current thread unless specified.",
1953 nullptr, eStepTypeOut, eStepScopeSource)));
1955 LoadSubCommand("step-over",
1956 CommandObjectSP(new CommandObjectThreadStepWithTypeAndScope(
1957 interpreter, "thread step-over",
1958 "Source level single step, stepping over calls. Defaults "
1959 "to current thread unless specified.",
1960 nullptr, eStepTypeOver, eStepScopeSource)));
1962 LoadSubCommand("step-inst",
1963 CommandObjectSP(new CommandObjectThreadStepWithTypeAndScope(
1964 interpreter, "thread step-inst",
1965 "Instruction level single step, stepping into calls. "
1966 "Defaults to current thread unless specified.",
1967 nullptr, eStepTypeTrace, eStepScopeInstruction)));
1969 LoadSubCommand("step-inst-over",
1970 CommandObjectSP(new CommandObjectThreadStepWithTypeAndScope(
1971 interpreter, "thread step-inst-over",
1972 "Instruction level single step, stepping over calls. "
1973 "Defaults to current thread unless specified.",
1974 nullptr, eStepTypeTraceOver, eStepScopeInstruction)));
1978 CommandObjectSP(new CommandObjectThreadStepWithTypeAndScope(
1979 interpreter, "thread step-scripted",
1980 "Step as instructed by the script class passed in the -C option.",
1981 nullptr, eStepTypeScripted, eStepScopeSource)));
1983 LoadSubCommand("plan", CommandObjectSP(new CommandObjectMultiwordThreadPlan(
1987 CommandObjectMultiwordThread::~CommandObjectMultiwordThread() = default;