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