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