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