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