LLDB mainline
CommandObjectThread.cpp
Go to the documentation of this file.
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
10
11#include <memory>
12#include <optional>
13#include <sstream>
14
16#include "CommandObjectTrace.h"
29#include "lldb/Target/Process.h"
32#include "lldb/Target/Target.h"
33#include "lldb/Target/Thread.h"
36#include "lldb/Target/Trace.h"
38#include "lldb/Utility/State.h"
40
41using namespace lldb;
42using namespace lldb_private;
43
44// CommandObjectThreadBacktrace
45#define LLDB_OPTIONS_thread_backtrace
46#include "CommandOptions.inc"
47
49public:
50 class CommandOptions : public Options {
51 public:
53 // Keep default values of all options in one place: OptionParsingStarting
54 // ()
55 OptionParsingStarting(nullptr);
56 }
57
58 ~CommandOptions() override = default;
59
60 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
61 ExecutionContext *execution_context) override {
63 const int short_option = m_getopt_table[option_idx].val;
64
65 switch (short_option) {
66 case 'c':
67 if (option_arg.getAsInteger(0, m_count)) {
70 "invalid integer value for option '%c': %s", short_option,
71 option_arg.data());
72 }
73 // A count of 0 means all frames.
74 if (m_count == 0)
76 break;
77 case 's':
78 if (option_arg.getAsInteger(0, m_start))
80 "invalid integer value for option '%c': %s", short_option,
81 option_arg.data());
82 break;
83 case 'e': {
84 bool success;
86 OptionArgParser::ToBoolean(option_arg, false, &success);
87 if (!success)
89 "invalid boolean value for option '%c': %s", short_option,
90 option_arg.data());
91 } break;
92 case 'u':
94 break;
95 case 'p': {
96 // Parse provider range using same format as breakpoint IDs.
97 // Supports: "N", "N-M", "N to M", "*", "all".
98 llvm::StringRef trimmed = option_arg.trim();
99 if (trimmed == "*" || trimmed.equals_insensitive("all")) {
102 break;
103 }
104
105 std::string option_lower = option_arg.lower();
106 static constexpr llvm::StringLiteral range_specifiers[] = {"-", "to"};
107
108 llvm::StringRef range_from;
109 llvm::StringRef range_to;
110 bool is_range = false;
111
112 // Try to find a range specifier.
113 for (auto specifier : range_specifiers) {
114 size_t idx = option_lower.find(specifier);
115 if (idx == std::string::npos)
116 continue;
117
118 range_from = llvm::StringRef(option_lower).take_front(idx).trim();
119 range_to = llvm::StringRef(option_lower)
120 .drop_front(idx + specifier.size())
121 .trim();
122
123 if (!range_from.empty() && !range_to.empty()) {
124 is_range = true;
125 break;
126 }
127 }
128
129 if (is_range) {
130 // Parse both start and end IDs.
131 if (range_from.getAsInteger(0, m_provider_start_id)) {
133 "invalid start provider ID for option '%c': %s", short_option,
134 range_from.data());
135 break;
136 }
137 if (range_to.getAsInteger(0, m_provider_end_id)) {
139 "invalid end provider ID for option '%c': %s", short_option,
140 range_to.data());
141 break;
142 }
143
144 // Validate range.
147 "invalid provider range for option '%c': start ID %u > end "
148 "ID %u",
150 break;
151 }
152 } else {
153 // Single provider ID.
154 if (option_arg.getAsInteger(0, m_provider_start_id)) {
156 "invalid provider ID for option '%c': %s", short_option,
157 option_arg.data());
158 break;
159 }
161 }
162
164 } break;
165 default:
166 llvm_unreachable("Unimplemented option");
167 }
168 return error;
169 }
170
171 void OptionParsingStarting(ExecutionContext *execution_context) override {
173 m_start = 0;
174 m_extended_backtrace = false;
179 m_show_all_providers = false;
180 }
181
182 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
183 return g_thread_backtrace_options;
184 }
185
186 // Instance variables to hold the values for command options.
187 uint32_t m_count;
188 uint32_t m_start;
195 };
196
199 interpreter, "thread backtrace",
200 "Show backtraces of thread call stacks. Defaults to the current "
201 "thread, thread indexes can be specified as arguments.\n"
202 "Use the thread-index \"all\" to see all threads.\n"
203 "Use the thread-index \"unique\" to see threads grouped by unique "
204 "call stacks.\n"
205 "Use '--provider <id>' or '--provider <start>-<end>' to view "
206 "synthetic frame providers (0=base unwinder, 1+=synthetic). "
207 "Range specifiers '-', 'to', 'To', 'TO' are supported.\n"
208 "Use 'settings set frame-format' to customize the printing of "
209 "frames in the backtrace and 'settings set thread-format' to "
210 "customize the thread header.\n"
211 "Customizable frame recognizers may filter out less interesting "
212 "frames, which results in gaps in the numbering. "
213 "Use '-u' to see all frames.",
214 nullptr,
215 eCommandRequiresProcess | eCommandRequiresThread |
216 eCommandTryTargetAPILock | eCommandProcessMustBeLaunched |
217 eCommandProcessMustBePaused) {}
218
219 ~CommandObjectThreadBacktrace() override = default;
220
221 Options *GetOptions() override { return &m_options; }
222
223 std::optional<std::string> GetRepeatCommand(Args &current_args,
224 uint32_t index) override {
225 llvm::StringRef count_opt("--count");
226 llvm::StringRef start_opt("--start");
227
228 // If no "count" was provided, we are dumping the entire backtrace, so
229 // there isn't a repeat command. So we search for the count option in
230 // the args, and if we find it, we make a copy and insert or modify the
231 // start option's value to start count indices greater.
232
233 Args copy_args(current_args);
234 size_t num_entries = copy_args.GetArgumentCount();
235 // These two point at the index of the option value if found.
236 size_t count_idx = 0;
237 size_t start_idx = 0;
238 size_t count_val = 0;
239 size_t start_val = 0;
240
241 for (size_t idx = 0; idx < num_entries; idx++) {
242 llvm::StringRef arg_string = copy_args[idx].ref();
243 if (arg_string == "-c" || count_opt.starts_with(arg_string)) {
244 idx++;
245 if (idx == num_entries)
246 return std::nullopt;
247 count_idx = idx;
248 if (copy_args[idx].ref().getAsInteger(0, count_val))
249 return std::nullopt;
250 } else if (arg_string == "-s" || start_opt.starts_with(arg_string)) {
251 idx++;
252 if (idx == num_entries)
253 return std::nullopt;
254 start_idx = idx;
255 if (copy_args[idx].ref().getAsInteger(0, start_val))
256 return std::nullopt;
257 }
258 }
259 if (count_idx == 0)
260 return std::nullopt;
261
262 std::string new_start_val = llvm::formatv("{0}", start_val + count_val);
263 if (start_idx == 0) {
264 copy_args.AppendArgument(start_opt);
265 copy_args.AppendArgument(new_start_val);
266 } else {
267 copy_args.ReplaceArgumentAtIndex(start_idx, new_start_val);
268 }
269 std::string repeat_command;
270 if (!copy_args.GetQuotedCommandString(repeat_command))
271 return std::nullopt;
272 return repeat_command;
273 }
274
275protected:
277 SystemRuntime *runtime = thread->GetProcess()->GetSystemRuntime();
278 if (runtime) {
279 Stream &strm = result.GetOutputStream();
280 const std::vector<ConstString> &types =
281 runtime->GetExtendedBacktraceTypes();
282 for (auto type : types) {
283 ThreadSP ext_thread_sp = runtime->GetExtendedBacktraceThread(
284 thread->shared_from_this(), type);
285 if (ext_thread_sp && ext_thread_sp->IsValid()) {
286 const uint32_t num_frames_with_source = 0;
287 const bool stop_format = false;
288 strm.PutChar('\n');
289 if (ext_thread_sp->GetStatus(strm, m_options.m_start,
290 m_options.m_count,
291 num_frames_with_source, stop_format,
292 !m_options.m_filtered_backtrace)) {
293 DoExtendedBacktrace(ext_thread_sp.get(), result);
294 }
295 }
296 }
297 }
298 }
299
300 bool HandleOneThread(lldb::tid_t tid, CommandReturnObject &result) override {
301 ThreadSP thread_sp =
302 m_exe_ctx.GetProcessPtr()->GetThreadList().FindThreadByID(tid);
303 if (!thread_sp) {
305 "thread disappeared while computing backtraces: 0x%" PRIx64 "\n",
306 tid);
307 return false;
308 }
309
310 Thread *thread = thread_sp.get();
311 Stream &strm = result.GetOutputStream();
312
313 // Check if provider filtering is requested.
314 if (m_options.m_provider_specific_backtrace) {
315 // Disallow 'bt --provider' from within a scripted frame provider.
316 // A provider's get_frame_at_index running 'bt --provider' would
317 // try to evaluate the very provider that is mid-construction,
318 // leading to infinite recursion.
319 if (thread->IsAnyProviderActive()) {
321 "cannot use '--provider' option while a scripted frame provider is "
322 "being constructed on this thread\n");
323 return false;
324 }
325
326 // Print thread status header, like regular bt. This also ensures the
327 // frame list is initialized and any providers are loaded.
328 thread->GetStatus(strm, /*start_frame=*/0, /*num_frames=*/0,
329 /*num_frames_with_source=*/0, /*stop_format=*/true,
330 /*show_hidden=*/false, /*only_stacks=*/false);
331
332 if (m_options.m_show_all_providers) {
333 // Show all providers: unwinder (0) through the last in the chain.
334 m_options.m_provider_start_id = 0;
335 const auto &chain = thread->GetProviderChainIds();
336 m_options.m_provider_end_id = chain.empty() ? 0 : chain.back().second;
337 }
338
339 // Provider filter mode: show sequential views for each provider in range.
340 bool first_provider = true;
341 for (lldb::frame_list_id_t provider_id = m_options.m_provider_start_id;
342 provider_id <= m_options.m_provider_end_id; ++provider_id) {
343
344 // Get the frame list for this provider.
345 lldb::StackFrameListSP frame_list_sp =
346 thread->GetFrameListByIdentifier(provider_id);
347
348 if (!frame_list_sp) {
349 // Provider doesn't exist - skip silently.
350 continue;
351 }
352
353 // Add blank line between providers for readability.
354 if (!first_provider)
355 strm.PutChar('\n');
356 first_provider = false;
357
358 // Print provider header.
359 strm.Printf("=== Provider %u", provider_id);
360
361 // Get provider metadata for header.
362 if (provider_id == 0) {
363 strm.Printf(": Base Unwinder ===\n");
364 } else {
365 // Find the descriptor in the provider chain.
366 const auto &provider_chain = thread->GetProviderChainIds();
367 std::string provider_name = "Unknown";
368 std::string provider_desc;
369 std::optional<uint32_t> provider_priority;
370
371 for (const auto &[descriptor, id] : provider_chain) {
372 if (id == provider_id) {
373 provider_name = descriptor.GetName().str();
374 provider_desc = descriptor.GetDescription();
375 provider_priority = descriptor.GetPriority();
376 break;
377 }
378 }
379
380 strm.Printf(": %s", provider_name.c_str());
381 if (provider_priority.has_value()) {
382 strm.Printf(" (priority: %u)", *provider_priority);
383 }
384 strm.Printf(" ===\n");
385
386 if (!provider_desc.empty()) {
387 strm.Printf("Description: %s\n", provider_desc.c_str());
388 }
389 }
390
391 // Print the backtrace for this provider.
392 const uint32_t num_frames_with_source = 0;
393 const StackFrameSP selected_frame_sp =
394 thread->GetSelectedFrame(DoNoSelectMostRelevantFrame);
395 const char *selected_frame_marker = selected_frame_sp ? "->" : nullptr;
396
397 size_t num_frames = frame_list_sp->GetStatus(
398 strm, m_options.m_start, m_options.m_count,
399 /*show_frame_info=*/true, num_frames_with_source,
400 /*show_unique=*/false,
401 /*show_hidden=*/!m_options.m_filtered_backtrace,
402 selected_frame_marker);
403
404 if (num_frames == 0) {
405 strm.Printf("(No frames available)\n");
406 }
407 }
408
409 if (first_provider) {
410 result.AppendErrorWithFormat("no provider found in range %u-%u\n",
411 m_options.m_provider_start_id,
412 m_options.m_provider_end_id);
413 return false;
414 }
415 return true;
416 }
417
418 // Original behavior: show default backtrace.
419 const bool only_stacks = m_unique_stacks;
420 const uint32_t num_frames_with_source = 0;
421 const bool stop_format = true;
422 if (!thread->GetStatus(strm, m_options.m_start, m_options.m_count,
423 num_frames_with_source, stop_format,
424 !m_options.m_filtered_backtrace, only_stacks)) {
426 "error displaying backtrace for thread: \"0x%4.4x\"\n",
427 thread->GetIndexID());
428 return false;
429 }
430 if (m_options.m_extended_backtrace) {
432 "Interrupt skipped extended backtrace")) {
433 DoExtendedBacktrace(thread, result);
434 }
435 }
436
437 return true;
438 }
439
441};
442
443#define LLDB_OPTIONS_thread_step_scope
444#include "CommandOptions.inc"
445
447public:
449 // Keep default values of all options in one place: OptionParsingStarting
450 // ()
451 OptionParsingStarting(nullptr);
452 }
453
454 ~ThreadStepScopeOptionGroup() override = default;
455
456 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
457 return llvm::ArrayRef(g_thread_step_scope_options);
458 }
459
460 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
461 ExecutionContext *execution_context) override {
463 const int short_option =
464 g_thread_step_scope_options[option_idx].short_option;
465
466 switch (short_option) {
467 case 'a': {
468 bool success;
469 bool avoid_no_debug =
470 OptionArgParser::ToBoolean(option_arg, true, &success);
471 if (!success)
473 "invalid boolean value for option '%c': %s", short_option,
474 option_arg.data());
475 else {
477 }
478 } break;
479
480 case 'A': {
481 bool success;
482 bool avoid_no_debug =
483 OptionArgParser::ToBoolean(option_arg, true, &success);
484 if (!success)
486 "invalid boolean value for option '%c': %s", short_option,
487 option_arg.data());
488 else {
490 }
491 } break;
492
493 case 'c':
494 if (option_arg.getAsInteger(0, m_step_count))
496 "invalid integer value for option '%c': %s", short_option,
497 option_arg.data());
498 break;
499
500 case 'm': {
501 auto enum_values = GetDefinitions()[option_idx].enum_values;
503 option_arg, enum_values, eOnlyDuringStepping, error);
504 } break;
505
506 case 'e':
507 if (option_arg == "block") {
509 break;
510 }
511 if (option_arg.getAsInteger(0, m_end_line))
513 "invalid end line number '%s'", option_arg.str().c_str());
514 break;
515
516 case 'r':
517 m_avoid_regexp.clear();
518 m_avoid_regexp.assign(std::string(option_arg));
519 break;
520
521 case 't':
522 m_step_in_target.clear();
523 m_step_in_target.assign(std::string(option_arg));
524 break;
525
526 default:
527 llvm_unreachable("Unimplemented option");
528 }
529 return error;
530 }
531
532 void OptionParsingStarting(ExecutionContext *execution_context) override {
536
537 // Check if we are in Non-Stop mode
538 TargetSP target_sp =
539 execution_context ? execution_context->GetTargetSP() : TargetSP();
540 ProcessSP process_sp =
541 execution_context ? execution_context->GetProcessSP() : ProcessSP();
542 if (process_sp && process_sp->GetSteppingRunsAllThreads())
544
545 m_avoid_regexp.clear();
546 m_step_in_target.clear();
547 m_step_count = 1;
550 }
551
552 // Instance variables to hold the values for command options.
556 std::string m_avoid_regexp;
557 std::string m_step_in_target;
558 uint32_t m_step_count;
559 uint32_t m_end_line;
561};
562
564public:
566 const char *name, const char *help,
567 const char *syntax,
568 StepType step_type)
569 : CommandObjectParsed(interpreter, name, help, syntax,
570 eCommandRequiresProcess | eCommandRequiresThread |
571 eCommandTryTargetAPILock |
572 eCommandProcessMustBeLaunched |
573 eCommandProcessMustBePaused),
574 m_step_type(step_type), m_class_options("scripted step") {
576
577 if (step_type == eStepTypeScripted) {
580 }
581 m_all_options.Append(&m_options);
582 m_all_options.Finalize();
583 }
584
586
587 void
589 OptionElementVector &opt_element_vector) override {
590 if (request.GetCursorIndex())
591 return;
592 CommandObject::HandleArgumentCompletion(request, opt_element_vector);
593 }
594
595 Options *GetOptions() override { return &m_all_options; }
596
597protected:
598 void DoExecute(Args &command, CommandReturnObject &result) override {
599 Process *process = m_exe_ctx.GetProcessPtr();
600 bool synchronous_execution = m_interpreter.GetSynchronous();
601
602 const uint32_t num_threads = process->GetThreadList().GetSize();
603 Thread *thread = nullptr;
604
605 if (command.GetArgumentCount() == 0) {
606 thread = GetDefaultThread();
607
608 if (thread == nullptr) {
609 result.AppendError("no selected thread in process");
610 return;
611 }
612 } else {
613 const char *thread_idx_cstr = command.GetArgumentAtIndex(0);
614 uint32_t step_thread_idx;
615
616 if (!llvm::to_integer(thread_idx_cstr, step_thread_idx)) {
617 result.AppendErrorWithFormat("invalid thread index '%s'.\n",
618 thread_idx_cstr);
619 return;
620 }
621 thread =
622 process->GetThreadList().FindThreadByIndexID(step_thread_idx).get();
623 if (thread == nullptr) {
625 "Thread index %u is out of range (valid values are 0 - %u).\n",
626 step_thread_idx, num_threads);
627 return;
628 }
629 }
630
632 if (m_class_options.GetName().empty()) {
633 result.AppendErrorWithFormat("empty class name for scripted step.");
634 return;
635 } else if (!GetDebugger().GetScriptInterpreter()->CheckObjectExists(
636 m_class_options.GetName().c_str())) {
638 "class for scripted step: \"%s\" does not exist.",
639 m_class_options.GetName().c_str());
640 return;
641 }
642 }
643
644 if (m_options.m_end_line != LLDB_INVALID_LINE_NUMBER &&
647 "end line option is only valid for step into");
648 return;
649 }
650
651 const bool abort_other_plans = false;
652 const lldb::RunMode stop_other_threads = m_options.m_run_mode;
653
654 // This is a bit unfortunate, but not all the commands in this command
655 // object support only while stepping, so I use the bool for them.
656 bool bool_stop_other_threads;
657 if (m_options.m_run_mode == eAllThreads)
658 bool_stop_other_threads = false;
659 else if (m_options.m_run_mode == eOnlyDuringStepping)
660 bool_stop_other_threads = (m_step_type != eStepTypeOut);
661 else
662 bool_stop_other_threads = true;
663
664 ThreadPlanSP new_plan_sp;
665 Status new_plan_status;
666
667 if (m_step_type == eStepTypeInto) {
668 StackFrame *frame = thread->GetStackFrameAtIndex(0).get();
669 assert(frame != nullptr);
670
671 if (frame->HasDebugInformation()) {
672 AddressRange range;
673 SymbolContext sc = frame->GetSymbolContext(eSymbolContextEverything);
674 if (m_options.m_end_line != LLDB_INVALID_LINE_NUMBER) {
675 llvm::Error err =
676 sc.GetAddressRangeFromHereToEndLine(m_options.m_end_line, range);
677 if (err) {
678 result.AppendErrorWithFormatv("invalid end-line option: {0}.",
679 llvm::toString(std::move(err)));
680 return;
681 }
682 } else if (m_options.m_end_line_is_block_end) {
684 Block *block = frame->GetSymbolContext(eSymbolContextBlock).block;
685 if (!block) {
686 result.AppendErrorWithFormat("Could not find the current block.");
687 return;
688 }
689
690 AddressRange block_range;
691 Address pc_address = frame->GetFrameCodeAddress();
692 block->GetRangeContainingAddress(pc_address, block_range);
693 if (!block_range.GetBaseAddress().IsValid()) {
695 "Could not find the current block address.");
696 return;
697 }
698 lldb::addr_t pc_offset_in_block =
699 pc_address.GetFileAddress() -
700 block_range.GetBaseAddress().GetFileAddress();
701 lldb::addr_t range_length =
702 block_range.GetByteSize() - pc_offset_in_block;
703 range = AddressRange(pc_address, range_length);
704 } else {
705 range = sc.line_entry.range;
706 }
707
708 new_plan_sp = thread->QueueThreadPlanForStepInRange(
709 abort_other_plans, range,
710 frame->GetSymbolContext(eSymbolContextEverything),
711 m_options.m_step_in_target.c_str(), stop_other_threads,
712 new_plan_status, m_options.m_step_in_avoid_no_debug,
713 m_options.m_step_out_avoid_no_debug);
714
715 if (new_plan_sp && !m_options.m_avoid_regexp.empty()) {
716 ThreadPlanStepInRange *step_in_range_plan =
717 static_cast<ThreadPlanStepInRange *>(new_plan_sp.get());
718 step_in_range_plan->SetAvoidRegexp(m_options.m_avoid_regexp.c_str());
719 }
720 } else
721 new_plan_sp = thread->QueueThreadPlanForStepSingleInstruction(
722 false, abort_other_plans, bool_stop_other_threads, new_plan_status);
723 } else if (m_step_type == eStepTypeOver) {
724 StackFrame *frame = thread->GetStackFrameAtIndex(0).get();
725
726 if (frame->HasDebugInformation())
727 new_plan_sp = thread->QueueThreadPlanForStepOverRange(
728 abort_other_plans,
729 frame->GetSymbolContext(eSymbolContextEverything).line_entry,
730 frame->GetSymbolContext(eSymbolContextEverything),
731 stop_other_threads, new_plan_status,
732 m_options.m_step_out_avoid_no_debug);
733 else
734 new_plan_sp = thread->QueueThreadPlanForStepSingleInstruction(
735 true, abort_other_plans, bool_stop_other_threads, new_plan_status);
736 } else if (m_step_type == eStepTypeTrace) {
737 new_plan_sp = thread->QueueThreadPlanForStepSingleInstruction(
738 false, abort_other_plans, bool_stop_other_threads, new_plan_status);
739 } else if (m_step_type == eStepTypeTraceOver) {
740 new_plan_sp = thread->QueueThreadPlanForStepSingleInstruction(
741 true, abort_other_plans, bool_stop_other_threads, new_plan_status);
742 } else if (m_step_type == eStepTypeOut) {
743 new_plan_sp = thread->QueueThreadPlanForStepOut(
744 abort_other_plans, nullptr, false, bool_stop_other_threads, eVoteYes,
746 thread->GetSelectedFrameIndex(DoNoSelectMostRelevantFrame),
747 new_plan_status, m_options.m_step_out_avoid_no_debug);
748 } else if (m_step_type == eStepTypeScripted) {
749 new_plan_sp = thread->QueueThreadPlanForStepScripted(
750 abort_other_plans, m_class_options.GetName().c_str(),
751 m_class_options.GetStructuredData(), bool_stop_other_threads,
752 new_plan_status);
753 } else {
754 result.AppendError("step type is not supported");
755 return;
756 }
757
758 // If we got a new plan, then set it to be a controlling plan (User level
759 // Plans should be controlling plans so that they can be interruptible).
760 // Then resume the process.
761
762 if (new_plan_sp) {
763 new_plan_sp->SetIsControllingPlan(true);
764 new_plan_sp->SetOkayToDiscard(false);
765
766 if (m_options.m_step_count > 1) {
767 if (!new_plan_sp->SetIterationCount(m_options.m_step_count)) {
768 result.AppendWarning(
769 "step operation does not support iteration count");
770 }
771 }
772
773 process->GetThreadList().SetSelectedThreadByID(thread->GetID());
774
775 const uint32_t iohandler_id = process->GetIOHandlerID();
776
777 StreamString stream;
779 if (synchronous_execution)
780 error = process->ResumeSynchronous(&stream);
781 else
782 error = process->Resume();
783
784 if (!error.Success()) {
785 result.AppendMessage(error.AsCString());
786 return;
787 }
788
789 // There is a race condition where this thread will return up the call
790 // stack to the main command handler and show an (lldb) prompt before
791 // HandlePrivateEvent (from PrivateStateThread) has a chance to call
792 // PushProcessIOHandler().
793 process->SyncIOHandler(iohandler_id, std::chrono::seconds(2));
794
795 if (synchronous_execution) {
796 // If any state changed events had anything to say, add that to the
797 // result
798 if (stream.GetSize() > 0)
799 result.AppendMessage(stream.GetString());
800
801 process->GetThreadList().SetSelectedThreadByID(thread->GetID());
802 result.SetDidChangeProcessState(true);
804 } else {
806 }
807 } else {
808 result.SetError(std::move(new_plan_status));
809 }
810 }
811
816};
817
818// CommandObjectThreadContinue
819
821public:
824 interpreter, "thread continue",
825 "Continue execution of the current target process. One "
826 "or more threads may be specified, by default all "
827 "threads continue.",
828 nullptr,
829 eCommandRequiresThread | eCommandTryTargetAPILock |
830 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused) {
832 }
833
834 ~CommandObjectThreadContinue() override = default;
835
836 void DoExecute(Args &command, CommandReturnObject &result) override {
837 bool synchronous_execution = m_interpreter.GetSynchronous();
838
839 Process *process = m_exe_ctx.GetProcessPtr();
840 if (process == nullptr) {
841 result.AppendError("no process exists. Cannot continue");
842 return;
843 }
844
845 StateType state = process->GetState();
846 if ((state == eStateCrashed) || (state == eStateStopped) ||
847 (state == eStateSuspended)) {
848 const size_t argc = command.GetArgumentCount();
849 if (argc > 0) {
850 // These two lines appear at the beginning of both blocks in this
851 // if..else, but that is because we need to release the lock before
852 // calling process->Resume below.
853 std::lock_guard<std::recursive_mutex> guard(
854 process->GetThreadList().GetMutex());
855 const uint32_t num_threads = process->GetThreadList().GetSize();
856 std::vector<Thread *> resume_threads;
857 for (auto &entry : command.entries()) {
858 uint32_t thread_idx;
859 if (entry.ref().getAsInteger(0, thread_idx)) {
861 "invalid thread index argument: \"%s\".\n", entry.c_str());
862 return;
863 }
864 Thread *thread =
865 process->GetThreadList().FindThreadByIndexID(thread_idx).get();
866
867 if (thread) {
868 resume_threads.push_back(thread);
869 } else {
870 result.AppendErrorWithFormat("invalid thread index %u.\n",
871 thread_idx);
872 return;
873 }
874 }
875
876 if (resume_threads.empty()) {
877 result.AppendError("no valid thread indexes were specified");
878 return;
879 } else {
880 Stream &strm = result.GetOutputStream();
881 if (resume_threads.size() == 1)
882 strm << "Resuming thread: ";
883 else
884 strm << "Resuming threads: ";
885
886 for (uint32_t idx = 0; idx < num_threads; ++idx) {
887 Thread *thread =
888 process->GetThreadList().GetThreadAtIndex(idx).get();
889 std::vector<Thread *>::iterator this_thread_pos =
890 find(resume_threads.begin(), resume_threads.end(), thread);
891
892 if (this_thread_pos != resume_threads.end()) {
893 resume_threads.erase(this_thread_pos);
894 if (!resume_threads.empty())
895 strm << llvm::formatv("{0}, ", thread->GetIndexID());
896 else
897 strm << llvm::formatv("{0} ", thread->GetIndexID());
898
899 const bool override_suspend = true;
900 thread->SetResumeState(eStateRunning, override_suspend);
901 } else {
902 thread->SetResumeState(eStateSuspended);
903 }
904 }
905 result.AppendMessageWithFormatv("in process {0}", process->GetID());
906 }
907 } else {
908 // These two lines appear at the beginning of both blocks in this
909 // if..else, but that is because we need to release the lock before
910 // calling process->Resume below.
911 std::lock_guard<std::recursive_mutex> guard(
912 process->GetThreadList().GetMutex());
913 const uint32_t num_threads = process->GetThreadList().GetSize();
914 Thread *current_thread = GetDefaultThread();
915 if (current_thread == nullptr) {
916 result.AppendError("the process doesn't have a current thread");
917 return;
918 }
919 // Set the actions that the threads should each take when resuming
920 for (uint32_t idx = 0; idx < num_threads; ++idx) {
921 Thread *thread = process->GetThreadList().GetThreadAtIndex(idx).get();
922 if (thread == current_thread) {
924 "Resuming thread {0:x4} in process {1}", thread->GetID(),
925 process->GetID());
926 const bool override_suspend = true;
927 thread->SetResumeState(eStateRunning, override_suspend);
928 } else {
929 thread->SetResumeState(eStateSuspended);
930 }
931 }
932 }
933
934 StreamString stream;
936 if (synchronous_execution)
937 error = process->ResumeSynchronous(&stream);
938 else
939 error = process->Resume();
940
941 // We should not be holding the thread list lock when we do this.
942 if (error.Success()) {
943 result.AppendMessageWithFormatv("Process {0} resuming",
944 process->GetID());
945 if (synchronous_execution) {
946 // If any state changed events had anything to say, add that to the
947 // result
948 if (stream.GetSize() > 0)
949 result.AppendMessage(stream.GetString());
950
951 result.SetDidChangeProcessState(true);
953 } else {
955 }
956 } else {
957 result.AppendErrorWithFormat("Failed to resume process: %s\n",
958 error.AsCString());
959 }
960 } else {
962 "Process cannot be continued from its current state (%s).\n",
963 StateAsCString(state));
964 }
965 }
966};
967
968// CommandObjectThreadUntil
969
970#define LLDB_OPTIONS_thread_until
971#include "CommandOptions.inc"
972
974public:
975 class CommandOptions : public Options {
976 public:
979
981 // Keep default values of all options in one place: OptionParsingStarting
982 // ()
983 OptionParsingStarting(nullptr);
984 }
985
986 ~CommandOptions() override = default;
987
988 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
989 ExecutionContext *execution_context) override {
991 const int short_option = m_getopt_table[option_idx].val;
992
993 switch (short_option) {
994 case 'a': {
996 execution_context, option_arg, LLDB_INVALID_ADDRESS, &error);
997 if (error.Success())
998 m_until_addrs.push_back(tmp_addr);
999 } break;
1000 case 't':
1001 if (option_arg.getAsInteger(0, m_thread_idx)) {
1003 error = Status::FromErrorStringWithFormat("invalid thread index '%s'",
1004 option_arg.str().c_str());
1005 }
1006 break;
1007 case 'f':
1008 if (option_arg.getAsInteger(0, m_frame_idx)) {
1010 error = Status::FromErrorStringWithFormat("invalid frame index '%s'",
1011 option_arg.str().c_str());
1012 }
1013 break;
1014 case 'm': {
1015 auto enum_values = GetDefinitions()[option_idx].enum_values;
1017 option_arg, enum_values, eOnlyDuringStepping, error);
1018
1019 if (error.Success()) {
1020 if (run_mode == eAllThreads)
1021 m_stop_others = false;
1022 else
1023 m_stop_others = true;
1024 }
1025 } break;
1026 default:
1027 llvm_unreachable("Unimplemented option");
1028 }
1029 return error;
1030 }
1031
1032 void OptionParsingStarting(ExecutionContext *execution_context) override {
1034 m_frame_idx = 0;
1035 m_stop_others = false;
1036 m_until_addrs.clear();
1037 }
1038
1039 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
1040 return llvm::ArrayRef(g_thread_until_options);
1041 }
1042
1043 bool m_stop_others = false;
1044 std::vector<lldb::addr_t> m_until_addrs;
1045
1046 // Instance variables to hold the values for command options.
1047 };
1048
1051 interpreter, "thread until",
1052 "Continue until a line number or address is reached by the "
1053 "current or specified thread. Stops when returning from "
1054 "the current function as a safety measure. "
1055 "The target line number(s) are given as arguments, and if more "
1056 "than one"
1057 " is provided, stepping will stop when the first one is hit.",
1058 nullptr,
1059 eCommandRequiresThread | eCommandTryTargetAPILock |
1060 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused) {
1062 }
1063
1064 ~CommandObjectThreadUntil() override = default;
1065
1066 Options *GetOptions() override { return &m_options; }
1067
1068protected:
1069 void DoExecute(Args &command, CommandReturnObject &result) override {
1070 bool synchronous_execution = m_interpreter.GetSynchronous();
1071
1072 Target *target = &GetTarget();
1073
1074 Process *process = m_exe_ctx.GetProcessPtr();
1075 if (process == nullptr) {
1076 result.AppendError("need a valid process to step");
1077 } else {
1078 Thread *thread = nullptr;
1079 std::vector<uint32_t> line_numbers;
1080
1081 if (command.GetArgumentCount() >= 1) {
1082 size_t num_args = command.GetArgumentCount();
1083 for (size_t i = 0; i < num_args; i++) {
1084 uint32_t line_number;
1085 if (!llvm::to_integer(command.GetArgumentAtIndex(i), line_number)) {
1086 result.AppendErrorWithFormat("invalid line number: '%s'.\n",
1087 command.GetArgumentAtIndex(i));
1088 return;
1089 } else
1090 line_numbers.push_back(line_number);
1091 }
1092 } else if (m_options.m_until_addrs.empty()) {
1093 result.AppendErrorWithFormat("No line number or address provided:\n%s",
1094 GetSyntax().str().c_str());
1095 return;
1096 }
1097
1098 if (m_options.m_thread_idx == LLDB_INVALID_THREAD_ID) {
1099 thread = GetDefaultThread();
1100 } else {
1101 thread = process->GetThreadList()
1102 .FindThreadByIndexID(m_options.m_thread_idx)
1103 .get();
1104 }
1105
1106 if (thread == nullptr) {
1107 const uint32_t num_threads = process->GetThreadList().GetSize();
1108 result.AppendErrorWithFormat(
1109 "Thread index %u is out of range (valid values are 0 - %u).\n",
1110 m_options.m_thread_idx, num_threads);
1111 return;
1112 }
1113
1114 const bool abort_other_plans = false;
1115
1116 StackFrame *frame =
1117 thread->GetStackFrameAtIndex(m_options.m_frame_idx).get();
1118 if (frame == nullptr) {
1119 result.AppendErrorWithFormat(
1120 "Frame index %u is out of range for thread id %" PRIu64 ".\n",
1121 m_options.m_frame_idx, thread->GetID());
1122 return;
1123 }
1124
1125 ThreadPlanSP new_plan_sp;
1126 Status new_plan_status;
1127
1128 if (frame->HasDebugInformation()) {
1129 // Finally we got here... Translate the given line number to a bunch
1130 // of addresses:
1131 SymbolContext sc(frame->GetSymbolContext(eSymbolContextCompUnit));
1132 LineTable *line_table = nullptr;
1133 if (sc.comp_unit)
1134 line_table = sc.comp_unit->GetLineTable();
1135
1136 if (line_table == nullptr) {
1137 result.AppendErrorWithFormat("Failed to resolve the line table for "
1138 "frame %u of thread id %" PRIu64 ".\n",
1139 m_options.m_frame_idx, thread->GetID());
1140 return;
1141 }
1142
1143 LineEntry function_start;
1144 std::vector<addr_t> address_list;
1145
1146 // Find the beginning & end index of the function, but first make
1147 // sure it is valid:
1148 if (!sc.function) {
1149 result.AppendErrorWithFormat("Have debug information but no "
1150 "function info - can't get until range.");
1151 return;
1152 }
1153
1154 RangeVector<uint32_t, uint32_t> line_idx_ranges;
1155 for (const AddressRange &range : sc.function->GetAddressRanges()) {
1156 auto [begin, end] = line_table->GetLineEntryIndexRange(range);
1157 line_idx_ranges.Append(begin, end - begin);
1158 }
1159 line_idx_ranges.Sort();
1160
1161 bool found_something = false;
1162
1163 // Since not all source lines will contribute code, check if we are
1164 // setting the breakpoint on the exact line number or the nearest
1165 // subsequent line number and set breakpoints at all the line table
1166 // entries of the chosen line number (exact or nearest subsequent).
1167 for (uint32_t line_number : line_numbers) {
1168 LineEntry line_entry;
1169 bool exact = false;
1170 if (sc.comp_unit->FindLineEntry(0, line_number, nullptr, exact,
1171 &line_entry) == UINT32_MAX)
1172 continue;
1173
1174 found_something = true;
1175 line_number = line_entry.line;
1176 exact = true;
1177 uint32_t end_func_idx = line_idx_ranges.GetMaxRangeEnd(0);
1178 uint32_t idx = sc.comp_unit->FindLineEntry(
1179 line_idx_ranges.GetMinRangeBase(UINT32_MAX), line_number, nullptr,
1180 exact, &line_entry);
1181 while (idx < end_func_idx) {
1182 if (line_idx_ranges.FindEntryIndexThatContains(idx) != UINT32_MAX) {
1183 addr_t address =
1184 line_entry.range.GetBaseAddress().GetLoadAddress(target);
1185 if (address != LLDB_INVALID_ADDRESS)
1186 address_list.push_back(address);
1187 }
1188 idx = sc.comp_unit->FindLineEntry(idx + 1, line_number, nullptr,
1189 exact, &line_entry);
1190 }
1191 }
1192
1193 for (lldb::addr_t address : m_options.m_until_addrs) {
1194 AddressRange unused;
1195 if (sc.function->GetRangeContainingLoadAddress(address, *target,
1196 unused))
1197 address_list.push_back(address);
1198 }
1199
1200 if (address_list.empty()) {
1201 if (found_something)
1202 result.AppendErrorWithFormat(
1203 "Until target outside of the current function.\n");
1204 else
1205 result.AppendErrorWithFormat(
1206 "No line entries matching until target.\n");
1207
1208 return;
1209 }
1210
1211 new_plan_sp = thread->QueueThreadPlanForStepUntil(
1212 abort_other_plans, address_list, m_options.m_stop_others,
1213 m_options.m_frame_idx, new_plan_status);
1214 if (new_plan_sp) {
1215 // User level plans should be controlling plans so they can be
1216 // interrupted
1217 // (e.g. by hitting a breakpoint) and other plans executed by the
1218 // user (stepping around the breakpoint) and then a "continue" will
1219 // resume the original plan.
1220 new_plan_sp->SetIsControllingPlan(true);
1221 new_plan_sp->SetOkayToDiscard(false);
1222 } else {
1223 result.SetError(std::move(new_plan_status));
1224 return;
1225 }
1226 } else {
1227 result.AppendErrorWithFormat("Frame index %u of thread id %" PRIu64
1228 " has no debug information.\n",
1229 m_options.m_frame_idx, thread->GetID());
1230 return;
1231 }
1232
1233 if (!process->GetThreadList().SetSelectedThreadByID(thread->GetID())) {
1234 result.AppendErrorWithFormat(
1235 "Failed to set the selected thread to thread id %" PRIu64 ".\n",
1236 thread->GetID());
1237 return;
1238 }
1239
1240 StreamString stream;
1241 Status error;
1242 if (synchronous_execution)
1243 error = process->ResumeSynchronous(&stream);
1244 else
1245 error = process->Resume();
1246
1247 if (error.Success()) {
1248 result.AppendMessageWithFormatv("Process {0} resuming",
1249 process->GetID());
1250 if (synchronous_execution) {
1251 // If any state changed events had anything to say, add that to the
1252 // result
1253 if (stream.GetSize() > 0)
1254 result.AppendMessage(stream.GetString());
1255
1256 result.SetDidChangeProcessState(true);
1258 } else {
1260 }
1261 } else {
1262 result.AppendErrorWithFormat("Failed to resume process: %s.\n",
1263 error.AsCString());
1264 }
1265 }
1266 }
1267
1269};
1270
1271// CommandObjectThreadSelect
1272
1273#define LLDB_OPTIONS_thread_select
1274#include "CommandOptions.inc"
1275
1277public:
1279 public:
1281
1282 ~OptionGroupThreadSelect() override = default;
1283
1284 void OptionParsingStarting(ExecutionContext *execution_context) override {
1286 }
1287
1288 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1289 ExecutionContext *execution_context) override {
1290 const int short_option = g_thread_select_options[option_idx].short_option;
1291 switch (short_option) {
1292 case 't': {
1293 if (option_arg.getAsInteger(0, m_thread_id)) {
1295 return Status::FromErrorStringWithFormat("Invalid thread ID: '%s'.",
1296 option_arg.str().c_str());
1297 }
1298 break;
1299 }
1300
1301 default:
1302 llvm_unreachable("Unimplemented option");
1303 }
1304
1305 return {};
1306 }
1307
1308 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
1309 return llvm::ArrayRef(g_thread_select_options);
1310 }
1311
1313 };
1314
1316 : CommandObjectParsed(interpreter, "thread select",
1317 "Change the currently selected thread.",
1318 "thread select <thread-index> (or -t <thread-id>)",
1319 eCommandRequiresProcess | eCommandTryTargetAPILock |
1320 eCommandProcessMustBeLaunched |
1321 eCommandProcessMustBePaused) {
1323 CommandArgumentData thread_idx_arg;
1324
1325 // Define the first (and only) variant of this arg.
1326 thread_idx_arg.arg_type = eArgTypeThreadIndex;
1327 thread_idx_arg.arg_repetition = eArgRepeatPlain;
1328 thread_idx_arg.arg_opt_set_association = LLDB_OPT_SET_1;
1329
1330 // There is only one variant this argument could be; put it into the
1331 // argument entry.
1332 arg.push_back(thread_idx_arg);
1333
1334 // Push the data for the first argument into the m_arguments vector.
1335 m_arguments.push_back(arg);
1336
1338 m_option_group.Finalize();
1339 }
1340
1341 ~CommandObjectThreadSelect() override = default;
1342
1343 void
1345 OptionElementVector &opt_element_vector) override {
1346 if (request.GetCursorIndex())
1347 return;
1348
1351 nullptr);
1352 }
1353
1354 Options *GetOptions() override { return &m_option_group; }
1355
1356protected:
1357 void DoExecute(Args &command, CommandReturnObject &result) override {
1358 Process *process = m_exe_ctx.GetProcessPtr();
1359 if (process == nullptr) {
1360 result.AppendError("no process");
1361 return;
1362 } else if (m_options.m_thread_id == LLDB_INVALID_THREAD_ID &&
1363 command.GetArgumentCount() != 1) {
1364 result.AppendErrorWithFormat(
1365 "'%s' takes exactly one thread index argument, or a thread ID "
1366 "option:\nUsage: %s\n",
1367 m_cmd_name.c_str(), m_cmd_syntax.c_str());
1368 return;
1369 } else if (m_options.m_thread_id != LLDB_INVALID_THREAD_ID &&
1370 command.GetArgumentCount() != 0) {
1371 result.AppendErrorWithFormat("'%s' cannot take both a thread ID option "
1372 "and a thread index argument:\nUsage: %s\n",
1373 m_cmd_name.c_str(), m_cmd_syntax.c_str());
1374 return;
1375 }
1376
1377 Thread *new_thread = nullptr;
1378 if (command.GetArgumentCount() == 1) {
1379 uint32_t index_id;
1380 if (!llvm::to_integer(command.GetArgumentAtIndex(0), index_id)) {
1381 result.AppendErrorWithFormat("Invalid thread index '%s'",
1382 command.GetArgumentAtIndex(0));
1383 return;
1384 }
1385 new_thread = process->GetThreadList().FindThreadByIndexID(index_id).get();
1386 if (new_thread == nullptr) {
1387 result.AppendErrorWithFormat("Invalid thread index #%s.\n",
1388 command.GetArgumentAtIndex(0));
1389 return;
1390 }
1391 } else {
1392 new_thread =
1393 process->GetThreadList().FindThreadByID(m_options.m_thread_id).get();
1394 if (new_thread == nullptr) {
1395 result.AppendErrorWithFormat("Invalid thread ID %" PRIu64 ".\n",
1396 m_options.m_thread_id);
1397 return;
1398 }
1399 }
1400
1401 process->GetThreadList().SetSelectedThreadByID(new_thread->GetID(), true);
1403 }
1404
1407};
1408
1409// CommandObjectThreadList
1410
1412public:
1415 interpreter, "thread list",
1416 "Show a summary of each thread in the current target process. "
1417 "Use 'settings set thread-format' to customize the individual "
1418 "thread listings.",
1419 "thread list",
1420 eCommandRequiresProcess | eCommandTryTargetAPILock |
1421 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused) {}
1422
1423 ~CommandObjectThreadList() override = default;
1424
1425protected:
1426 void DoExecute(Args &command, CommandReturnObject &result) override {
1427 Stream &strm = result.GetOutputStream();
1429 Process *process = m_exe_ctx.GetProcessPtr();
1430 const bool only_threads_with_stop_reason = false;
1431 const uint32_t start_frame = 0;
1432 const uint32_t num_frames = 0;
1433 const uint32_t num_frames_with_source = 0;
1434 process->GetStatus(strm);
1435 process->GetThreadStatus(strm, only_threads_with_stop_reason, start_frame,
1436 num_frames, num_frames_with_source, false);
1437 }
1438};
1439
1440// CommandObjectThreadInfo
1441#define LLDB_OPTIONS_thread_info
1442#include "CommandOptions.inc"
1443
1445public:
1446 class CommandOptions : public Options {
1447 public:
1449
1450 ~CommandOptions() override = default;
1451
1452 void OptionParsingStarting(ExecutionContext *execution_context) override {
1453 m_json_thread = false;
1454 m_json_stopinfo = false;
1455 m_backing_thread = false;
1456 }
1457
1458 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1459 ExecutionContext *execution_context) override {
1460 const int short_option = m_getopt_table[option_idx].val;
1461 Status error;
1462
1463 switch (short_option) {
1464 case 'j':
1465 m_json_thread = true;
1466 break;
1467
1468 case 's':
1469 m_json_stopinfo = true;
1470 break;
1471
1472 case 'b':
1473 m_backing_thread = true;
1474 break;
1475
1476 default:
1477 llvm_unreachable("Unimplemented option");
1478 }
1479 return error;
1480 }
1481
1482 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
1483 return llvm::ArrayRef(g_thread_info_options);
1484 }
1485
1489 };
1490
1493 interpreter, "thread info",
1494 "Show an extended summary of one or "
1495 "more threads. Defaults to the "
1496 "current thread.",
1497 "thread info",
1498 eCommandRequiresProcess | eCommandTryTargetAPILock |
1499 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused) {
1500 m_add_return = false;
1501 }
1502
1503 ~CommandObjectThreadInfo() override = default;
1504
1505 void
1512
1513 Options *GetOptions() override { return &m_options; }
1514
1516 ThreadSP thread_sp =
1517 m_exe_ctx.GetProcessPtr()->GetThreadList().FindThreadByID(tid);
1518 if (!thread_sp) {
1519 result.AppendErrorWithFormat("thread no longer exists: 0x%" PRIx64 "\n",
1520 tid);
1521 return false;
1522 }
1523
1524 Thread *thread = thread_sp.get();
1525 if (m_options.m_backing_thread && thread->GetBackingThread())
1526 thread = thread->GetBackingThread().get();
1527
1528 Stream &strm = result.GetOutputStream();
1529 if (!thread->GetDescription(strm, eDescriptionLevelFull,
1530 m_options.m_json_thread,
1531 m_options.m_json_stopinfo)) {
1532 result.AppendErrorWithFormat("error displaying info for thread: \"%d\"\n",
1533 thread->GetIndexID());
1534 return false;
1535 }
1536 return true;
1537 }
1538
1540};
1541
1542// CommandObjectThreadException
1543
1545public:
1548 interpreter, "thread exception",
1549 "Display the current exception object for a thread. Defaults to "
1550 "the current thread.",
1551 "thread exception",
1552 eCommandRequiresProcess | eCommandTryTargetAPILock |
1553 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused) {}
1554
1555 ~CommandObjectThreadException() override = default;
1556
1557 void
1564
1566 ThreadSP thread_sp =
1567 m_exe_ctx.GetProcessPtr()->GetThreadList().FindThreadByID(tid);
1568 if (!thread_sp) {
1569 result.AppendErrorWithFormat("thread no longer exists: 0x%" PRIx64 "\n",
1570 tid);
1571 return false;
1572 }
1573
1574 Stream &strm = result.GetOutputStream();
1575 ValueObjectSP exception_object_sp = thread_sp->GetCurrentException();
1576 if (exception_object_sp) {
1577 if (llvm::Error error = exception_object_sp->Dump(strm)) {
1578 result.AppendError(toString(std::move(error)));
1579 return false;
1580 }
1581 }
1582
1583 ThreadSP exception_thread_sp = thread_sp->GetCurrentExceptionBacktrace();
1584 if (exception_thread_sp && exception_thread_sp->IsValid()) {
1585 const uint32_t num_frames_with_source = 0;
1586 const bool stop_format = false;
1587 exception_thread_sp->GetStatus(strm, 0, UINT32_MAX,
1588 num_frames_with_source, stop_format,
1589 /*filtered*/ false);
1590 }
1591
1592 return true;
1593 }
1594};
1595
1597public:
1600 interpreter, "thread siginfo",
1601 "Display the current siginfo object for a thread. Defaults to "
1602 "the current thread.",
1603 "thread siginfo",
1604 eCommandRequiresProcess | eCommandTryTargetAPILock |
1605 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused) {}
1606
1607 ~CommandObjectThreadSiginfo() override = default;
1608
1609 void
1616
1618 ThreadSP thread_sp =
1619 m_exe_ctx.GetProcessPtr()->GetThreadList().FindThreadByID(tid);
1620 if (!thread_sp) {
1621 result.AppendErrorWithFormat("thread no longer exists: 0x%" PRIx64 "\n",
1622 tid);
1623 return false;
1624 }
1625
1626 Stream &strm = result.GetOutputStream();
1627 if (!thread_sp->GetDescription(strm, eDescriptionLevelFull, false, false)) {
1628 result.AppendErrorWithFormat("error displaying info for thread: \"%d\"\n",
1629 thread_sp->GetIndexID());
1630 return false;
1631 }
1632 ValueObjectSP exception_object_sp = thread_sp->GetSiginfoValue();
1633 if (exception_object_sp) {
1634 if (llvm::Error error = exception_object_sp->Dump(strm)) {
1635 result.AppendError(toString(std::move(error)));
1636 return false;
1637 }
1638 } else
1639 strm.Printf("(no siginfo)\n");
1640 strm.PutChar('\n');
1641
1642 return true;
1643 }
1644};
1645
1646// CommandObjectThreadReturn
1647#define LLDB_OPTIONS_thread_return
1648#include "CommandOptions.inc"
1649
1651public:
1652 class CommandOptions : public Options {
1653 public:
1655 // Keep default values of all options in one place: OptionParsingStarting
1656 // ()
1657 OptionParsingStarting(nullptr);
1658 }
1659
1660 ~CommandOptions() override = default;
1661
1662 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1663 ExecutionContext *execution_context) override {
1664 Status error;
1665 const int short_option = m_getopt_table[option_idx].val;
1666
1667 switch (short_option) {
1668 case 'x': {
1669 bool success;
1670 bool tmp_value =
1671 OptionArgParser::ToBoolean(option_arg, false, &success);
1672 if (success)
1673 m_from_expression = tmp_value;
1674 else {
1676 "invalid boolean value '%s' for 'x' option",
1677 option_arg.str().c_str());
1678 }
1679 } break;
1680 default:
1681 llvm_unreachable("Unimplemented option");
1682 }
1683 return error;
1684 }
1685
1686 void OptionParsingStarting(ExecutionContext *execution_context) override {
1687 m_from_expression = false;
1688 }
1689
1690 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
1691 return llvm::ArrayRef(g_thread_return_options);
1692 }
1693
1694 bool m_from_expression = false;
1695
1696 // Instance variables to hold the values for command options.
1697 };
1698
1700 : CommandObjectRaw(interpreter, "thread return",
1701 "Prematurely return from a stack frame, "
1702 "short-circuiting execution of newer frames "
1703 "and optionally yielding a specified value. Defaults "
1704 "to the exiting the current stack "
1705 "frame.",
1706 "thread return",
1707 eCommandRequiresFrame | eCommandTryTargetAPILock |
1708 eCommandProcessMustBeLaunched |
1709 eCommandProcessMustBePaused) {
1711 }
1712
1713 ~CommandObjectThreadReturn() override = default;
1714
1715 Options *GetOptions() override { return &m_options; }
1716
1717protected:
1718 void DoExecute(llvm::StringRef command,
1719 CommandReturnObject &result) override {
1720 // I am going to handle this by hand, because I don't want you to have to
1721 // say:
1722 // "thread return -- -5".
1723 if (command.starts_with("-x")) {
1724 if (command.size() != 2U)
1725 result.AppendWarning("return values ignored when returning from user "
1726 "called expressions");
1727
1728 Thread *thread = m_exe_ctx.GetThreadPtr();
1729 Status error;
1730 error = thread->UnwindInnermostExpression();
1731 if (!error.Success()) {
1732 result.AppendErrorWithFormat("Unwinding expression failed - %s.",
1733 error.AsCString());
1734 } else {
1735 bool success =
1736 thread->SetSelectedFrameByIndexNoisily(0, result.GetOutputStream());
1737 if (success) {
1738 m_exe_ctx.SetFrameSP(
1739 thread->GetSelectedFrame(DoNoSelectMostRelevantFrame));
1741 } else {
1742 result.AppendErrorWithFormat(
1743 "Could not select 0th frame after unwinding expression.");
1744 }
1745 }
1746 return;
1747 }
1748
1749 ValueObjectSP return_valobj_sp;
1750
1751 StackFrameSP frame_sp = m_exe_ctx.GetFrameSP();
1752 uint32_t frame_idx = frame_sp->GetFrameIndex();
1753
1754 if (frame_sp->IsInlined()) {
1755 result.AppendError("don't know how to return from inlined frames");
1756 return;
1757 }
1758
1759 if (!command.empty()) {
1760 Target *target = m_exe_ctx.GetTargetPtr();
1762
1763 options.SetUnwindOnError(true);
1765
1767 exe_results = target->EvaluateExpression(command, frame_sp.get(),
1768 return_valobj_sp, options);
1769 if (exe_results != eExpressionCompleted) {
1770 if (return_valobj_sp)
1771 result.AppendErrorWithFormat(
1772 "Error evaluating result expression: %s",
1773 return_valobj_sp->GetError().AsCString());
1774 else
1775 result.AppendErrorWithFormat(
1776 "Unknown error evaluating result expression.");
1777 return;
1778 }
1779 }
1780
1781 Status error;
1782 ThreadSP thread_sp = m_exe_ctx.GetThreadSP();
1783 const bool broadcast = true;
1784 error = thread_sp->ReturnFromFrame(frame_sp, return_valobj_sp, broadcast);
1785 if (!error.Success()) {
1786 result.AppendErrorWithFormat(
1787 "Error returning from frame %d of thread %d: %s.", frame_idx,
1788 thread_sp->GetIndexID(), error.AsCString());
1789 return;
1790 }
1791
1793 }
1794
1796};
1797
1798// CommandObjectThreadJump
1799#define LLDB_OPTIONS_thread_jump
1800#include "CommandOptions.inc"
1801
1803public:
1804 class CommandOptions : public Options {
1805 public:
1807
1808 ~CommandOptions() override = default;
1809
1810 void OptionParsingStarting(ExecutionContext *execution_context) override {
1811 m_filenames.Clear();
1812 m_line_num = 0;
1813 m_line_offset = 0;
1815 m_force = false;
1816 }
1817
1818 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1819 ExecutionContext *execution_context) override {
1820 const int short_option = m_getopt_table[option_idx].val;
1821 Status error;
1822
1823 switch (short_option) {
1824 case 'f':
1825 m_filenames.AppendIfUnique(FileSpec(option_arg));
1826 if (m_filenames.GetSize() > 1)
1827 return Status::FromErrorString("only one source file expected.");
1828 break;
1829 case 'l':
1830 if (option_arg.getAsInteger(0, m_line_num))
1831 return Status::FromErrorStringWithFormat("invalid line number: '%s'.",
1832 option_arg.str().c_str());
1833 break;
1834 case 'b': {
1835 option_arg.consume_front("+");
1836
1837 if (option_arg.getAsInteger(0, m_line_offset))
1838 return Status::FromErrorStringWithFormat("invalid line offset: '%s'.",
1839 option_arg.str().c_str());
1840 break;
1841 }
1842 case 'a':
1843 m_load_addr = OptionArgParser::ToAddress(execution_context, option_arg,
1845 break;
1846 case 'r':
1847 m_force = true;
1848 break;
1849 default:
1850 llvm_unreachable("Unimplemented option");
1851 }
1852 return error;
1853 }
1854
1855 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
1856 return llvm::ArrayRef(g_thread_jump_options);
1857 }
1858
1860 uint32_t m_line_num;
1864 };
1865
1868 interpreter, "thread jump",
1869 "Sets the program counter to a new address.", "thread jump",
1870 eCommandRequiresFrame | eCommandTryTargetAPILock |
1871 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused) {}
1872
1873 ~CommandObjectThreadJump() override = default;
1874
1875 Options *GetOptions() override { return &m_options; }
1876
1877protected:
1878 void DoExecute(Args &args, CommandReturnObject &result) override {
1879 RegisterContext *reg_ctx = m_exe_ctx.GetRegisterContext();
1880 StackFrame *frame = m_exe_ctx.GetFramePtr();
1881 Thread *thread = m_exe_ctx.GetThreadPtr();
1882 Target *target = m_exe_ctx.GetTargetPtr();
1883 const SymbolContext &sym_ctx =
1884 frame->GetSymbolContext(eSymbolContextLineEntry);
1885
1886 if (m_options.m_load_addr != LLDB_INVALID_ADDRESS) {
1887 // Use this address directly.
1888 Address dest = Address(m_options.m_load_addr);
1889
1890 lldb::addr_t callAddr = dest.GetCallableLoadAddress(target);
1891 if (callAddr == LLDB_INVALID_ADDRESS) {
1892 result.AppendErrorWithFormat("Invalid destination address.");
1893 return;
1894 }
1895
1896 if (!reg_ctx->SetPC(callAddr)) {
1897 result.AppendErrorWithFormat("Error changing PC value for thread %d.",
1898 thread->GetIndexID());
1899 return;
1900 }
1901 } else {
1902 // Pick either the absolute line, or work out a relative one.
1903 int32_t line = (int32_t)m_options.m_line_num;
1904 if (line == 0)
1905 line = sym_ctx.line_entry.line + m_options.m_line_offset;
1906
1907 // Try the current file, but override if asked.
1908 FileSpec file = sym_ctx.line_entry.GetFile();
1909 if (m_options.m_filenames.GetSize() == 1)
1910 file = m_options.m_filenames.GetFileSpecAtIndex(0);
1911
1912 if (!file) {
1913 result.AppendErrorWithFormat(
1914 "no source file available for the current location");
1915 return;
1916 }
1917
1918 std::string warnings;
1919 Status err = thread->JumpToLine(file, line, m_options.m_force, &warnings);
1920
1921 if (err.Fail()) {
1922 result.SetError(std::move(err));
1923 return;
1924 }
1925
1926 if (!warnings.empty())
1927 result.AppendWarning(warnings.c_str());
1928 }
1929
1931 }
1932
1934};
1935
1936// Next are the subcommands of CommandObjectMultiwordThreadPlan
1937
1938// CommandObjectThreadPlanList
1939#define LLDB_OPTIONS_thread_plan_list
1940#include "CommandOptions.inc"
1941
1943public:
1944 class CommandOptions : public Options {
1945 public:
1947 // Keep default values of all options in one place: OptionParsingStarting
1948 // ()
1949 OptionParsingStarting(nullptr);
1950 }
1951
1952 ~CommandOptions() override = default;
1953
1954 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1955 ExecutionContext *execution_context) override {
1956 const int short_option = m_getopt_table[option_idx].val;
1957
1958 switch (short_option) {
1959 case 'i':
1960 m_internal = true;
1961 break;
1962 case 't':
1963 lldb::tid_t tid;
1964 if (option_arg.getAsInteger(0, tid))
1965 return Status::FromErrorStringWithFormat("invalid tid: '%s'.",
1966 option_arg.str().c_str());
1967 m_tids.push_back(tid);
1968 break;
1969 case 'u':
1970 m_unreported = false;
1971 break;
1972 case 'v':
1973 m_verbose = true;
1974 break;
1975 default:
1976 llvm_unreachable("Unimplemented option");
1977 }
1978 return {};
1979 }
1980
1981 void OptionParsingStarting(ExecutionContext *execution_context) override {
1982 m_verbose = false;
1983 m_internal = false;
1984 m_unreported = true; // The variable is "skip unreported" and we want to
1985 // skip unreported by default.
1986 m_tids.clear();
1987 }
1988
1989 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
1990 return llvm::ArrayRef(g_thread_plan_list_options);
1991 }
1992
1993 // Instance variables to hold the values for command options.
1997 std::vector<lldb::tid_t> m_tids;
1998 };
1999
2002 interpreter, "thread plan list",
2003 "Show thread plans for one or more threads. If no threads are "
2004 "specified, show the "
2005 "current thread. Use the thread-index \"all\" to see all threads.",
2006 nullptr,
2007 eCommandRequiresProcess | eCommandRequiresThread |
2008 eCommandTryTargetAPILock | eCommandProcessMustBeLaunched |
2009 eCommandProcessMustBePaused) {}
2010
2011 ~CommandObjectThreadPlanList() override = default;
2012
2013 Options *GetOptions() override { return &m_options; }
2014
2015 void DoExecute(Args &command, CommandReturnObject &result) override {
2016 // If we are reporting all threads, dispatch to the Process to do that:
2017 if (command.GetArgumentCount() == 0 && m_options.m_tids.empty()) {
2018 Stream &strm = result.GetOutputStream();
2019 DescriptionLevel desc_level = m_options.m_verbose
2022 m_exe_ctx.GetProcessPtr()->DumpThreadPlans(
2023 strm, desc_level, m_options.m_internal, true, m_options.m_unreported);
2025 return;
2026 } else {
2027 // Do any TID's that the user may have specified as TID, then do any
2028 // Thread Indexes...
2029 if (!m_options.m_tids.empty()) {
2030 Process *process = m_exe_ctx.GetProcessPtr();
2031 StreamString tmp_strm;
2032 for (lldb::tid_t tid : m_options.m_tids) {
2033 bool success = process->DumpThreadPlansForTID(
2034 tmp_strm, tid, eDescriptionLevelFull, m_options.m_internal,
2035 true /* condense_trivial */, m_options.m_unreported);
2036 // If we didn't find a TID, stop here and return an error.
2037 if (!success) {
2038 result.AppendError("Error dumping plans:");
2039 result.AppendError(tmp_strm.GetString());
2040 return;
2041 }
2042 // Otherwise, add our data to the output:
2043 result.GetOutputStream() << tmp_strm.GetString();
2044 }
2045 }
2046 return CommandObjectIterateOverThreads::DoExecute(command, result);
2047 }
2048 }
2049
2050protected:
2052 // If we have already handled this from a -t option, skip it here.
2053 if (llvm::is_contained(m_options.m_tids, tid))
2054 return true;
2055
2056 Process *process = m_exe_ctx.GetProcessPtr();
2057
2058 Stream &strm = result.GetOutputStream();
2060 if (m_options.m_verbose)
2061 desc_level = eDescriptionLevelVerbose;
2062
2063 process->DumpThreadPlansForTID(strm, tid, desc_level, m_options.m_internal,
2064 true /* condense_trivial */,
2065 m_options.m_unreported);
2066 return true;
2067 }
2068
2070};
2071
2073public:
2075 : CommandObjectParsed(interpreter, "thread plan discard",
2076 "Discards thread plans up to and including the "
2077 "specified index (see 'thread plan list'.) "
2078 "Only user visible plans can be discarded.",
2079 nullptr,
2080 eCommandRequiresProcess | eCommandRequiresThread |
2081 eCommandTryTargetAPILock |
2082 eCommandProcessMustBeLaunched |
2083 eCommandProcessMustBePaused) {
2085 }
2086
2088
2089 void
2091 OptionElementVector &opt_element_vector) override {
2092 if (!m_exe_ctx.HasThreadScope() || request.GetCursorIndex())
2093 return;
2094
2095 m_exe_ctx.GetThreadPtr()->AutoCompleteThreadPlans(request);
2096 }
2097
2098 void DoExecute(Args &args, CommandReturnObject &result) override {
2099 Thread *thread = m_exe_ctx.GetThreadPtr();
2100 if (args.GetArgumentCount() != 1) {
2101 result.AppendErrorWithFormat("Too many arguments, expected one - the "
2102 "thread plan index - but got %zu.",
2103 args.GetArgumentCount());
2104 return;
2105 }
2106
2107 uint32_t thread_plan_idx;
2108 if (!llvm::to_integer(args.GetArgumentAtIndex(0), thread_plan_idx)) {
2109 result.AppendErrorWithFormat(
2110 "Invalid thread index: \"%s\" - should be unsigned int.",
2111 args.GetArgumentAtIndex(0));
2112 return;
2113 }
2114
2115 if (thread_plan_idx == 0) {
2116 result.AppendErrorWithFormat(
2117 "You wouldn't really want me to discard the base thread plan.");
2118 return;
2119 }
2120
2121 if (thread->DiscardUserThreadPlansUpToIndex(thread_plan_idx)) {
2123 } else {
2124 result.AppendErrorWithFormat(
2125 "Could not find User thread plan with index %s.",
2126 args.GetArgumentAtIndex(0));
2127 }
2128 }
2129};
2130
2132public:
2134 : CommandObjectParsed(interpreter, "thread plan prune",
2135 "Removes any thread plans associated with "
2136 "currently unreported threads. "
2137 "Specify one or more TID's to remove, or if no "
2138 "TID's are provides, remove threads for all "
2139 "unreported threads",
2140 nullptr,
2141 eCommandRequiresProcess |
2142 eCommandTryTargetAPILock |
2143 eCommandProcessMustBeLaunched |
2144 eCommandProcessMustBePaused) {
2146 }
2147
2148 ~CommandObjectThreadPlanPrune() override = default;
2149
2150 void DoExecute(Args &args, CommandReturnObject &result) override {
2151 Process *process = m_exe_ctx.GetProcessPtr();
2152
2153 if (args.GetArgumentCount() == 0) {
2154 process->PruneThreadPlans();
2156 return;
2157 }
2158
2159 const size_t num_args = args.GetArgumentCount();
2160
2161 std::lock_guard<std::recursive_mutex> guard(
2162 process->GetThreadList().GetMutex());
2163
2164 for (size_t i = 0; i < num_args; i++) {
2165 lldb::tid_t tid;
2166 if (!llvm::to_integer(args.GetArgumentAtIndex(i), tid)) {
2167 result.AppendErrorWithFormat("invalid thread specification: \"%s\"\n",
2168 args.GetArgumentAtIndex(i));
2169 return;
2170 }
2171 if (!process->PruneThreadPlansForTID(tid)) {
2172 result.AppendErrorWithFormat("Could not find unreported tid: \"%s\"\n",
2173 args.GetArgumentAtIndex(i));
2174 return;
2175 }
2176 }
2178 }
2179};
2180
2181// CommandObjectMultiwordThreadPlan
2182
2184public:
2187 interpreter, "plan",
2188 "Commands for managing thread plans that control execution.",
2189 "thread plan <subcommand> [<subcommand objects]") {
2191 "list", CommandObjectSP(new CommandObjectThreadPlanList(interpreter)));
2193 "discard",
2196 "prune",
2198 }
2199
2201};
2202
2203// Next are the subcommands of CommandObjectMultiwordTrace
2204
2205// CommandObjectTraceExport
2206
2208public:
2211 interpreter, "trace thread export",
2212 "Commands for exporting traces of the threads in the current "
2213 "process to different formats.",
2214 "thread trace export <export-plugin> [<subcommand objects>]") {
2215
2216 for (auto &cbs : PluginManager::GetTraceExporterCallbacks()) {
2217 if (cbs.create_thread_trace_export_command)
2218 LoadSubCommand(cbs.name,
2219 cbs.create_thread_trace_export_command(interpreter));
2220 }
2221 }
2222};
2223
2224// CommandObjectTraceStart
2225
2227public:
2230 /*live_debug_session_only=*/true, interpreter, "thread trace start",
2231 "Start tracing threads with the corresponding trace "
2232 "plug-in for the current process.",
2233 "thread trace start [<trace-options>]") {}
2234
2235protected:
2239};
2240
2241// CommandObjectTraceStop
2242
2244public:
2247 interpreter, "thread trace stop",
2248 "Stop tracing threads, including the ones traced with the "
2249 "\"process trace start\" command."
2250 "Defaults to the current thread. Thread indices can be "
2251 "specified as arguments.\n Use the thread-index \"all\" to stop "
2252 "tracing "
2253 "for all existing threads.",
2254 "thread trace stop [<thread-index> <thread-index> ...]",
2255 eCommandRequiresProcess | eCommandTryTargetAPILock |
2256 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused |
2257 eCommandProcessMustBeTraced) {}
2258
2259 ~CommandObjectTraceStop() override = default;
2260
2262 llvm::ArrayRef<lldb::tid_t> tids) override {
2263 ProcessSP process_sp = m_exe_ctx.GetProcessSP();
2264
2265 TraceSP trace_sp = process_sp->GetTarget().GetTrace();
2266
2267 if (llvm::Error err = trace_sp->Stop(tids))
2268 result.AppendError(toString(std::move(err)));
2269 else
2271
2272 return result.Succeeded();
2273 }
2274};
2275
2277 CommandReturnObject &result) {
2278 if (args.GetArgumentCount() == 0)
2279 return exe_ctx.GetThreadSP();
2280
2281 const char *arg = args.GetArgumentAtIndex(0);
2282 uint32_t thread_idx;
2283
2284 if (!llvm::to_integer(arg, thread_idx)) {
2285 result.AppendErrorWithFormat("invalid thread specification: \"%s\"\n", arg);
2286 return nullptr;
2287 }
2288 ThreadSP thread_sp =
2289 exe_ctx.GetProcessRef().GetThreadList().FindThreadByIndexID(thread_idx);
2290 if (!thread_sp)
2291 result.AppendErrorWithFormat("no thread with index: \"%s\"\n", arg);
2292 return thread_sp;
2293}
2294
2295// CommandObjectTraceDumpFunctionCalls
2296#define LLDB_OPTIONS_thread_trace_dump_function_calls
2297#include "CommandOptions.inc"
2298
2300public:
2301 class CommandOptions : public Options {
2302 public:
2304
2305 ~CommandOptions() override = default;
2306
2307 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
2308 ExecutionContext *execution_context) override {
2309 Status error;
2310 const int short_option = m_getopt_table[option_idx].val;
2311
2312 switch (short_option) {
2313 case 'j': {
2314 m_dumper_options.json = true;
2315 break;
2316 }
2317 case 'J': {
2318 m_dumper_options.json = true;
2319 m_dumper_options.pretty_print_json = true;
2320 break;
2321 }
2322 case 'F': {
2323 m_output_file.emplace(option_arg);
2324 break;
2325 }
2326 default:
2327 llvm_unreachable("Unimplemented option");
2328 }
2329 return error;
2330 }
2331
2332 void OptionParsingStarting(ExecutionContext *execution_context) override {
2333 m_dumper_options = {};
2334 m_output_file = std::nullopt;
2335 }
2336
2337 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
2338 return llvm::ArrayRef(g_thread_trace_dump_function_calls_options);
2339 }
2340
2341 static const size_t kDefaultCount = 20;
2342
2343 // Instance variables to hold the values for command options.
2345 std::optional<FileSpec> m_output_file;
2346 };
2347
2350 interpreter, "thread trace dump function-calls",
2351 "Dump the traced function-calls for one thread. If no "
2352 "thread is specified, the current thread is used.",
2353 nullptr,
2354 eCommandRequiresProcess | eCommandRequiresThread |
2355 eCommandTryTargetAPILock | eCommandProcessMustBeLaunched |
2356 eCommandProcessMustBePaused | eCommandProcessMustBeTraced) {
2358 }
2359
2361
2362 Options *GetOptions() override { return &m_options; }
2363
2364protected:
2365 void DoExecute(Args &args, CommandReturnObject &result) override {
2366 ThreadSP thread_sp = GetSingleThreadFromArgs(m_exe_ctx, args, result);
2367 if (!thread_sp) {
2368 result.AppendError("invalid thread\n");
2369 return;
2370 }
2371
2372 llvm::Expected<TraceCursorSP> cursor_or_error =
2373 m_exe_ctx.GetTargetSP()->GetTrace()->CreateNewCursor(*thread_sp);
2374
2375 if (!cursor_or_error) {
2376 result.AppendError(llvm::toString(cursor_or_error.takeError()));
2377 return;
2378 }
2379 TraceCursorSP &cursor_sp = *cursor_or_error;
2380
2381 std::optional<StreamFile> out_file;
2382 if (m_options.m_output_file) {
2383 out_file.emplace(m_options.m_output_file->GetPath().c_str(),
2386 }
2387
2388 m_options.m_dumper_options.forwards = true;
2389
2390 TraceDumper dumper(std::move(cursor_sp),
2391 out_file ? *out_file : result.GetOutputStream(),
2392 m_options.m_dumper_options);
2393
2394 dumper.DumpFunctionCalls();
2395 }
2396
2398};
2399
2400// CommandObjectTraceDumpInstructions
2401#define LLDB_OPTIONS_thread_trace_dump_instructions
2402#include "CommandOptions.inc"
2403
2405public:
2406 class CommandOptions : public Options {
2407 public:
2409
2410 ~CommandOptions() override = default;
2411
2412 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
2413 ExecutionContext *execution_context) override {
2414 Status error;
2415 const int short_option = m_getopt_table[option_idx].val;
2416
2417 switch (short_option) {
2418 case 'c': {
2419 int32_t count;
2420 if (option_arg.empty() || option_arg.getAsInteger(0, count) ||
2421 count < 0)
2423 "invalid integer value for option '%s'",
2424 option_arg.str().c_str());
2425 else
2426 m_count = count;
2427 break;
2428 }
2429 case 'a': {
2430 m_count = std::numeric_limits<decltype(m_count)>::max();
2431 break;
2432 }
2433 case 's': {
2434 int32_t skip;
2435 if (option_arg.empty() || option_arg.getAsInteger(0, skip) || skip < 0)
2437 "invalid integer value for option '%s'",
2438 option_arg.str().c_str());
2439 else
2440 m_dumper_options.skip = skip;
2441 break;
2442 }
2443 case 'i': {
2444 uint64_t id;
2445 if (option_arg.empty() || option_arg.getAsInteger(0, id))
2447 "invalid integer value for option '%s'",
2448 option_arg.str().c_str());
2449 else
2450 m_dumper_options.id = id;
2451 break;
2452 }
2453 case 'F': {
2454 m_output_file.emplace(option_arg);
2455 break;
2456 }
2457 case 'r': {
2458 m_dumper_options.raw = true;
2459 break;
2460 }
2461 case 'f': {
2462 m_dumper_options.forwards = true;
2463 break;
2464 }
2465 case 'k': {
2466 m_dumper_options.show_control_flow_kind = true;
2467 break;
2468 }
2469 case 't': {
2470 m_dumper_options.show_timestamps = true;
2471 break;
2472 }
2473 case 'e': {
2474 m_dumper_options.show_events = true;
2475 break;
2476 }
2477 case 'j': {
2478 m_dumper_options.json = true;
2479 break;
2480 }
2481 case 'J': {
2482 m_dumper_options.pretty_print_json = true;
2483 m_dumper_options.json = true;
2484 break;
2485 }
2486 case 'E': {
2487 m_dumper_options.only_events = true;
2488 m_dumper_options.show_events = true;
2489 break;
2490 }
2491 case 'C': {
2492 m_continue = true;
2493 break;
2494 }
2495 default:
2496 llvm_unreachable("Unimplemented option");
2497 }
2498 return error;
2499 }
2500
2501 void OptionParsingStarting(ExecutionContext *execution_context) override {
2503 m_continue = false;
2504 m_output_file = std::nullopt;
2505 m_dumper_options = {};
2506 }
2507
2508 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
2509 return llvm::ArrayRef(g_thread_trace_dump_instructions_options);
2510 }
2511
2512 static const size_t kDefaultCount = 20;
2513
2514 // Instance variables to hold the values for command options.
2515 size_t m_count;
2517 std::optional<FileSpec> m_output_file;
2519 };
2520
2523 interpreter, "thread trace dump instructions",
2524 "Dump the traced instructions for one thread. If no "
2525 "thread is specified, show the current thread.",
2526 nullptr,
2527 eCommandRequiresProcess | eCommandRequiresThread |
2528 eCommandTryTargetAPILock | eCommandProcessMustBeLaunched |
2529 eCommandProcessMustBePaused | eCommandProcessMustBeTraced) {
2531 }
2532
2534
2535 Options *GetOptions() override { return &m_options; }
2536
2537 std::optional<std::string> GetRepeatCommand(Args &current_command_args,
2538 uint32_t index) override {
2539 std::string cmd;
2540 current_command_args.GetCommandString(cmd);
2541 if (cmd.find(" --continue") == std::string::npos)
2542 cmd += " --continue";
2543 return cmd;
2544 }
2545
2546protected:
2547 void DoExecute(Args &args, CommandReturnObject &result) override {
2548 ThreadSP thread_sp = GetSingleThreadFromArgs(m_exe_ctx, args, result);
2549 if (!thread_sp) {
2550 result.AppendError("invalid thread\n");
2551 return;
2552 }
2553
2554 if (m_options.m_continue && m_last_id) {
2555 // We set up the options to continue one instruction past where
2556 // the previous iteration stopped.
2557 m_options.m_dumper_options.skip = 1;
2558 m_options.m_dumper_options.id = m_last_id;
2559 }
2560
2561 llvm::Expected<TraceCursorSP> cursor_or_error =
2562 m_exe_ctx.GetTargetSP()->GetTrace()->CreateNewCursor(*thread_sp);
2563
2564 if (!cursor_or_error) {
2565 result.AppendError(llvm::toString(cursor_or_error.takeError()));
2566 return;
2567 }
2568 TraceCursorSP &cursor_sp = *cursor_or_error;
2569
2570 if (m_options.m_dumper_options.id &&
2571 !cursor_sp->HasId(*m_options.m_dumper_options.id)) {
2572 result.AppendError("invalid instruction id\n");
2573 return;
2574 }
2575
2576 std::optional<StreamFile> out_file;
2577 if (m_options.m_output_file) {
2578 out_file.emplace(m_options.m_output_file->GetPath().c_str(),
2581 }
2582
2583 if (m_options.m_continue && !m_last_id) {
2584 // We need to stop processing data when we already ran out of instructions
2585 // in a previous command. We can fake this by setting the cursor past the
2586 // end of the trace.
2587 cursor_sp->Seek(1, lldb::eTraceCursorSeekTypeEnd);
2588 }
2589
2590 TraceDumper dumper(std::move(cursor_sp),
2591 out_file ? *out_file : result.GetOutputStream(),
2592 m_options.m_dumper_options);
2593
2594 m_last_id = dumper.DumpInstructions(m_options.m_count);
2595 }
2596
2598 // Last traversed id used to continue a repeat command. std::nullopt means
2599 // that all the trace has been consumed.
2600 std::optional<lldb::user_id_t> m_last_id;
2601};
2602
2603// CommandObjectTraceDumpInfo
2604#define LLDB_OPTIONS_thread_trace_dump_info
2605#include "CommandOptions.inc"
2606
2608public:
2609 class CommandOptions : public Options {
2610 public:
2612
2613 ~CommandOptions() override = default;
2614
2615 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
2616 ExecutionContext *execution_context) override {
2617 Status error;
2618 const int short_option = m_getopt_table[option_idx].val;
2619
2620 switch (short_option) {
2621 case 'v': {
2622 m_verbose = true;
2623 break;
2624 }
2625 case 'j': {
2626 m_json = true;
2627 break;
2628 }
2629 default:
2630 llvm_unreachable("Unimplemented option");
2631 }
2632 return error;
2633 }
2634
2635 void OptionParsingStarting(ExecutionContext *execution_context) override {
2636 m_verbose = false;
2637 m_json = false;
2638 }
2639
2640 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
2641 return llvm::ArrayRef(g_thread_trace_dump_info_options);
2642 }
2643
2644 // Instance variables to hold the values for command options.
2647 };
2648
2651 interpreter, "thread trace dump info",
2652 "Dump the traced information for one or more threads. If no "
2653 "threads are specified, show the current thread. Use the "
2654 "thread-index \"all\" to see all threads.",
2655 nullptr,
2656 eCommandRequiresProcess | eCommandTryTargetAPILock |
2657 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused |
2658 eCommandProcessMustBeTraced) {}
2659
2660 ~CommandObjectTraceDumpInfo() override = default;
2661
2662 Options *GetOptions() override { return &m_options; }
2663
2664protected:
2666 const TraceSP &trace_sp = m_exe_ctx.GetTargetSP()->GetTrace();
2667 ThreadSP thread_sp =
2668 m_exe_ctx.GetProcessPtr()->GetThreadList().FindThreadByID(tid);
2669 trace_sp->DumpTraceInfo(*thread_sp, result.GetOutputStream(),
2670 m_options.m_verbose, m_options.m_json);
2671 return true;
2672 }
2673
2675};
2676
2677// CommandObjectMultiwordTraceDump
2679public:
2682 interpreter, "dump",
2683 "Commands for displaying trace information of the threads "
2684 "in the current process.",
2685 "thread trace dump <subcommand> [<subcommand objects>]") {
2687 "instructions",
2690 "function-calls",
2693 "info", CommandObjectSP(new CommandObjectTraceDumpInfo(interpreter)));
2694 }
2696};
2697
2698// CommandObjectMultiwordTrace
2700public:
2703 interpreter, "trace",
2704 "Commands for operating on traces of the threads in the current "
2705 "process.",
2706 "thread trace <subcommand> [<subcommand objects>]") {
2708 interpreter)));
2709 LoadSubCommand("start",
2710 CommandObjectSP(new CommandObjectTraceStart(interpreter)));
2711 LoadSubCommand("stop",
2712 CommandObjectSP(new CommandObjectTraceStop(interpreter)));
2713 LoadSubCommand("export",
2714 CommandObjectSP(new CommandObjectTraceExport(interpreter)));
2715 }
2716
2717 ~CommandObjectMultiwordTrace() override = default;
2718};
2719
2720// CommandObjectMultiwordThread
2721
2723 CommandInterpreter &interpreter)
2724 : CommandObjectMultiword(interpreter, "thread",
2725 "Commands for operating on "
2726 "one or more threads in "
2727 "the current process.",
2728 "thread <subcommand> [<subcommand-options>]") {
2730 interpreter)));
2731 LoadSubCommand("continue",
2733 LoadSubCommand("list",
2734 CommandObjectSP(new CommandObjectThreadList(interpreter)));
2735 LoadSubCommand("return",
2736 CommandObjectSP(new CommandObjectThreadReturn(interpreter)));
2737 LoadSubCommand("jump",
2738 CommandObjectSP(new CommandObjectThreadJump(interpreter)));
2739 LoadSubCommand("select",
2740 CommandObjectSP(new CommandObjectThreadSelect(interpreter)));
2741 LoadSubCommand("until",
2742 CommandObjectSP(new CommandObjectThreadUntil(interpreter)));
2743 LoadSubCommand("info",
2744 CommandObjectSP(new CommandObjectThreadInfo(interpreter)));
2746 interpreter)));
2747 LoadSubCommand("siginfo",
2749 LoadSubCommand("step-in",
2751 interpreter, "thread step-in",
2752 "Source level single step, stepping into calls. Defaults "
2753 "to current thread unless specified.",
2754 nullptr, eStepTypeInto)));
2755
2756 LoadSubCommand("step-out",
2758 interpreter, "thread step-out",
2759 "Finish executing the current stack frame and stop after "
2760 "returning. Defaults to current thread unless specified.",
2761 nullptr, eStepTypeOut)));
2762
2763 LoadSubCommand("step-over",
2765 interpreter, "thread step-over",
2766 "Source level single step, stepping over calls. Defaults "
2767 "to current thread unless specified.",
2768 nullptr, eStepTypeOver)));
2769
2770 LoadSubCommand("step-inst",
2772 interpreter, "thread step-inst",
2773 "Instruction level single step, stepping into calls. "
2774 "Defaults to current thread unless specified.",
2775 nullptr, eStepTypeTrace)));
2776
2777 LoadSubCommand("step-inst-over",
2779 interpreter, "thread step-inst-over",
2780 "Instruction level single step, stepping over calls. "
2781 "Defaults to current thread unless specified.",
2782 nullptr, eStepTypeTraceOver)));
2783
2785 "step-scripted",
2787 interpreter, "thread step-scripted",
2788 "Step as instructed by the script class passed in the -C option. "
2789 "You can also specify a dictionary of key (-k) and value (-v) pairs "
2790 "that will be used to populate an SBStructuredData Dictionary, which "
2791 "will be passed to the constructor of the class implementing the "
2792 "scripted step. See the Python Reference for more details.",
2793 nullptr, eStepTypeScripted)));
2794
2796 interpreter)));
2797 LoadSubCommand("trace",
2799}
2800
static ThreadSP GetSingleThreadFromArgs(ExecutionContext &exe_ctx, Args &args, CommandReturnObject &result)
static llvm::raw_ostream & error(Stream &strm)
#define INTERRUPT_REQUESTED(debugger,...)
This handy define will keep you from having to generate a report for the interruption by hand.
Definition Debugger.h:494
static void skip(TSLexer *lexer)
~CommandObjectMultiwordThreadPlan() override=default
CommandObjectMultiwordThreadPlan(CommandInterpreter &interpreter)
~CommandObjectMultiwordTraceDump() override=default
CommandObjectMultiwordTraceDump(CommandInterpreter &interpreter)
CommandObjectMultiwordTrace(CommandInterpreter &interpreter)
~CommandObjectMultiwordTrace() override=default
void OptionParsingStarting(ExecutionContext *execution_context) override
Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, ExecutionContext *execution_context) override
Set the value of an option.
llvm::ArrayRef< OptionDefinition > GetDefinitions() override
CommandObjectThreadBacktrace(CommandInterpreter &interpreter)
std::optional< std::string > GetRepeatCommand(Args &current_args, uint32_t index) override
Get the command that appropriate for a "repeat" of the current command.
void DoExtendedBacktrace(Thread *thread, CommandReturnObject &result)
bool HandleOneThread(lldb::tid_t tid, CommandReturnObject &result) override
~CommandObjectThreadBacktrace() override=default
~CommandObjectThreadContinue() override=default
void DoExecute(Args &command, CommandReturnObject &result) override
CommandObjectThreadContinue(CommandInterpreter &interpreter)
CommandObjectThreadException(CommandInterpreter &interpreter)
bool HandleOneThread(lldb::tid_t tid, CommandReturnObject &result) override
~CommandObjectThreadException() override=default
void HandleArgumentCompletion(CompletionRequest &request, OptionElementVector &opt_element_vector) override
The default version handles argument definitions that have only one argument type,...
llvm::ArrayRef< OptionDefinition > GetDefinitions() override
void OptionParsingStarting(ExecutionContext *execution_context) override
Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, ExecutionContext *execution_context) override
Set the value of an option.
void HandleArgumentCompletion(CompletionRequest &request, OptionElementVector &opt_element_vector) override
The default version handles argument definitions that have only one argument type,...
CommandObjectThreadInfo(CommandInterpreter &interpreter)
bool HandleOneThread(lldb::tid_t tid, CommandReturnObject &result) override
~CommandObjectThreadInfo() override=default
Options * GetOptions() override
Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, ExecutionContext *execution_context) override
Set the value of an option.
llvm::ArrayRef< OptionDefinition > GetDefinitions() override
void OptionParsingStarting(ExecutionContext *execution_context) override
CommandObjectThreadJump(CommandInterpreter &interpreter)
void DoExecute(Args &args, CommandReturnObject &result) override
~CommandObjectThreadJump() override=default
Options * GetOptions() override
void DoExecute(Args &command, CommandReturnObject &result) override
~CommandObjectThreadList() override=default
CommandObjectThreadList(CommandInterpreter &interpreter)
void DoExecute(Args &args, CommandReturnObject &result) override
CommandObjectThreadPlanDiscard(CommandInterpreter &interpreter)
~CommandObjectThreadPlanDiscard() override=default
void HandleArgumentCompletion(CompletionRequest &request, OptionElementVector &opt_element_vector) override
The default version handles argument definitions that have only one argument type,...
llvm::ArrayRef< OptionDefinition > GetDefinitions() override
Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, ExecutionContext *execution_context) override
Set the value of an option.
void OptionParsingStarting(ExecutionContext *execution_context) override
CommandObjectThreadPlanList(CommandInterpreter &interpreter)
bool HandleOneThread(lldb::tid_t tid, CommandReturnObject &result) override
~CommandObjectThreadPlanList() override=default
void DoExecute(Args &command, CommandReturnObject &result) override
CommandObjectThreadPlanPrune(CommandInterpreter &interpreter)
~CommandObjectThreadPlanPrune() override=default
void DoExecute(Args &args, CommandReturnObject &result) override
Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, ExecutionContext *execution_context) override
Set the value of an option.
void OptionParsingStarting(ExecutionContext *execution_context) override
llvm::ArrayRef< OptionDefinition > GetDefinitions() override
CommandObjectThreadReturn(CommandInterpreter &interpreter)
void DoExecute(llvm::StringRef command, CommandReturnObject &result) override
~CommandObjectThreadReturn() override=default
Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, ExecutionContext *execution_context) override
void OptionParsingStarting(ExecutionContext *execution_context) override
llvm::ArrayRef< OptionDefinition > GetDefinitions() override
void DoExecute(Args &command, CommandReturnObject &result) override
void HandleArgumentCompletion(CompletionRequest &request, OptionElementVector &opt_element_vector) override
The default version handles argument definitions that have only one argument type,...
CommandObjectThreadSelect(CommandInterpreter &interpreter)
~CommandObjectThreadSelect() override=default
OptionGroupThreadSelect m_options
~CommandObjectThreadSiginfo() override=default
bool HandleOneThread(lldb::tid_t tid, CommandReturnObject &result) override
CommandObjectThreadSiginfo(CommandInterpreter &interpreter)
void HandleArgumentCompletion(CompletionRequest &request, OptionElementVector &opt_element_vector) override
The default version handles argument definitions that have only one argument type,...
OptionGroupPythonClassWithDict m_class_options
~CommandObjectThreadStepWithTypeAndScope() override=default
void DoExecute(Args &command, CommandReturnObject &result) override
void HandleArgumentCompletion(CompletionRequest &request, OptionElementVector &opt_element_vector) override
The default version handles argument definitions that have only one argument type,...
CommandObjectThreadStepWithTypeAndScope(CommandInterpreter &interpreter, const char *name, const char *help, const char *syntax, StepType step_type)
llvm::ArrayRef< OptionDefinition > GetDefinitions() override
Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, ExecutionContext *execution_context) override
Set the value of an option.
void OptionParsingStarting(ExecutionContext *execution_context) override
CommandObjectThreadUntil(CommandInterpreter &interpreter)
~CommandObjectThreadUntil() override=default
void DoExecute(Args &command, CommandReturnObject &result) override
llvm::ArrayRef< OptionDefinition > GetDefinitions() override
void OptionParsingStarting(ExecutionContext *execution_context) override
Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, ExecutionContext *execution_context) override
Set the value of an option.
void DoExecute(Args &args, CommandReturnObject &result) override
CommandObjectTraceDumpFunctionCalls(CommandInterpreter &interpreter)
~CommandObjectTraceDumpFunctionCalls() override=default
Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, ExecutionContext *execution_context) override
Set the value of an option.
void OptionParsingStarting(ExecutionContext *execution_context) override
llvm::ArrayRef< OptionDefinition > GetDefinitions() override
~CommandObjectTraceDumpInfo() override=default
bool HandleOneThread(lldb::tid_t tid, CommandReturnObject &result) override
CommandObjectTraceDumpInfo(CommandInterpreter &interpreter)
llvm::ArrayRef< OptionDefinition > GetDefinitions() override
Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, ExecutionContext *execution_context) override
Set the value of an option.
void OptionParsingStarting(ExecutionContext *execution_context) override
CommandObjectTraceDumpInstructions(CommandInterpreter &interpreter)
~CommandObjectTraceDumpInstructions() override=default
std::optional< std::string > GetRepeatCommand(Args &current_command_args, uint32_t index) override
Get the command that appropriate for a "repeat" of the current command.
void DoExecute(Args &args, CommandReturnObject &result) override
std::optional< lldb::user_id_t > m_last_id
CommandObjectTraceExport(CommandInterpreter &interpreter)
lldb::CommandObjectSP GetDelegateCommand(Trace &trace) override
CommandObjectTraceStart(CommandInterpreter &interpreter)
~CommandObjectTraceStop() override=default
bool DoExecuteOnThreads(Args &command, CommandReturnObject &result, llvm::ArrayRef< lldb::tid_t > tids) override
CommandObjectTraceStop(CommandInterpreter &interpreter)
void OptionParsingStarting(ExecutionContext *execution_context) override
~ThreadStepScopeOptionGroup() override=default
Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, ExecutionContext *execution_context) override
llvm::ArrayRef< OptionDefinition > GetDefinitions() override
A section + offset based address range class.
Address & GetBaseAddress()
Get accessor for the base address of the range.
lldb::addr_t GetByteSize() const
Get accessor for the byte size of this range.
A section + offset based address class.
Definition Address.h:62
lldb::addr_t GetLoadAddress(Target *target) const
Get the load address.
Definition Address.cpp:301
lldb::addr_t GetCallableLoadAddress(Target *target, bool is_indirect=false) const
Get the load address as a callable code load address.
Definition Address.cpp:326
lldb::addr_t GetFileAddress() const
Get the file address.
Definition Address.cpp:281
bool IsValid() const
Check if the object state is valid.
Definition Address.h:355
A command line argument class.
Definition Args.h:33
size_t GetArgumentCount() const
Gets the number of arguments left in this command object.
Definition Args.h:120
void ReplaceArgumentAtIndex(size_t idx, llvm::StringRef arg_str, char quote_char='\0')
Replaces the argument value at index idx to arg_str if idx is a valid argument index.
Definition Args.cpp:347
void AppendArgument(llvm::StringRef arg_str, char quote_char='\0')
Appends a new argument to the end of the list argument list.
Definition Args.cpp:332
llvm::ArrayRef< ArgEntry > entries() const
Definition Args.h:132
const char * GetArgumentAtIndex(size_t idx) const
Gets the NULL terminated C string argument pointer for the argument at index idx.
Definition Args.cpp:273
bool GetCommandString(std::string &command) const
Definition Args.cpp:215
bool GetQuotedCommandString(std::string &command) const
Definition Args.cpp:232
A class that describes a single lexical block.
Definition Block.h:41
bool GetRangeContainingAddress(const Address &addr, AddressRange &range)
Definition Block.cpp:248
static bool InvokeCommonCompletionCallbacks(CommandInterpreter &interpreter, uint32_t completion_mask, lldb_private::CompletionRequest &request, SearchFilter *searcher)
CommandObjectIterateOverThreads(CommandInterpreter &interpreter, const char *name, const char *help, const char *syntax, uint32_t flags)
void DoExecute(Args &command, CommandReturnObject &result) override
CommandObjectMultipleThreads(CommandInterpreter &interpreter, const char *name, const char *help, const char *syntax, uint32_t flags)
CommandObjectMultiwordThread(CommandInterpreter &interpreter)
bool LoadSubCommand(llvm::StringRef cmd_name, const lldb::CommandObjectSP &command_obj) override
CommandObjectMultiword(CommandInterpreter &interpreter, const char *name, const char *help=nullptr, const char *syntax=nullptr, uint32_t flags=0)
CommandObjectParsed(CommandInterpreter &interpreter, const char *name, const char *help=nullptr, const char *syntax=nullptr, uint32_t flags=0)
CommandObjectRaw(CommandInterpreter &interpreter, llvm::StringRef name, llvm::StringRef help="", llvm::StringRef syntax="", uint32_t flags=0)
CommandObjectTraceProxy(bool live_debug_session_only, CommandInterpreter &interpreter, const char *name, const char *help=nullptr, const char *syntax=nullptr, uint32_t flags=0)
std::vector< CommandArgumentData > CommandArgumentEntry
void AddSimpleArgumentList(lldb::CommandArgumentType arg_type, ArgumentRepetitionType repetition_type=eArgRepeatPlain)
std::vector< CommandArgumentEntry > m_arguments
CommandInterpreter & GetCommandInterpreter()
CommandInterpreter & m_interpreter
virtual void HandleArgumentCompletion(CompletionRequest &request, OptionElementVector &opt_element_vector)
The default version handles argument definitions that have only one argument type,...
virtual llvm::StringRef GetSyntax()
void AppendMessage(llvm::StringRef in_string)
void AppendError(llvm::StringRef in_string)
void SetStatus(lldb::ReturnStatus status)
void AppendErrorWithFormat(const char *format,...) __attribute__((format(printf
void void AppendMessageWithFormatv(const char *format, Args &&...args)
void AppendWarning(llvm::StringRef in_string)
void AppendErrorWithFormatv(const char *format, Args &&...args)
uint32_t FindLineEntry(uint32_t start_idx, uint32_t line, const FileSpec *file_spec_ptr, bool exact, LineEntry *line_entry)
Find the line entry by line and optional inlined file spec.
LineTable * GetLineTable()
Get the line table for the compile unit.
"lldb/Utility/ArgCompletionRequest.h"
void SetUnwindOnError(bool unwind=false)
Definition Target.h:390
void SetUseDynamic(lldb::DynamicValueType dynamic=lldb::eDynamicCanRunTarget)
Definition Target.h:405
"lldb/Target/ExecutionContext.h" A class that contains an execution context.
const lldb::TargetSP & GetTargetSP() const
Get accessor to get the target shared pointer.
const lldb::ProcessSP & GetProcessSP() const
Get accessor to get the process shared pointer.
Process & GetProcessRef() const
Returns a reference to the process object.
const lldb::ThreadSP & GetThreadSP() const
Get accessor to get the thread shared pointer.
A file collection class.
A file utility class.
Definition FileSpec.h:57
@ eOpenOptionWriteOnly
Definition File.h:52
@ eOpenOptionCanCreate
Definition File.h:56
@ eOpenOptionTruncate
Definition File.h:57
bool GetRangeContainingLoadAddress(lldb::addr_t load_addr, Target &target, AddressRange &range)
Definition Function.h:455
AddressRanges GetAddressRanges()
Definition Function.h:448
A line table class.
Definition LineTable.h:25
std::pair< uint32_t, uint32_t > GetLineEntryIndexRange(const AddressRange &range) const
Returns the (half-open) range of line entry indexes which overlap the given address range.
A command line option parsing protocol class.
Definition Options.h:58
std::vector< Option > m_getopt_table
Definition Options.h:198
static llvm::SmallVector< TraceExporterCallbacks > GetTraceExporterCallbacks()
A plug-in interface definition class for debugging a process.
Definition Process.h:355
lldb::pid_t GetID() const
Returns the pid of the process or LLDB_INVALID_PROCESS_ID if there is no known pid.
Definition Process.h:538
ThreadList & GetThreadList()
Definition Process.h:2312
Status Resume()
Resumes all of a process's threads as configured using the Thread run control functions.
Definition Process.cpp:1309
void PruneThreadPlans()
Prune ThreadPlanStacks for all unreported threads.
Definition Process.cpp:1203
bool PruneThreadPlansForTID(lldb::tid_t tid)
Prune ThreadPlanStacks for unreported threads.
Definition Process.cpp:1199
virtual SystemRuntime * GetSystemRuntime()
Get the system runtime plug-in for this process.
Definition Process.cpp:2986
bool DumpThreadPlansForTID(Stream &strm, lldb::tid_t tid, lldb::DescriptionLevel desc_level, bool internal, bool condense_trivial, bool skip_unreported_plans)
Dump the thread plans associated with thread with tid.
Definition Process.cpp:1207
Status ResumeSynchronous(Stream *stream)
Resume a process, and wait for it to stop.
Definition Process.cpp:1326
size_t GetThreadStatus(Stream &ostrm, bool only_threads_with_stop_reason, uint32_t start_frame, uint32_t num_frames, uint32_t num_frames_with_source, bool stop_format)
Definition Process.cpp:5986
lldb::StateType GetState()
Get accessor for the current process state.
Definition Process.cpp:1259
void GetStatus(Stream &ostrm)
Definition Process.cpp:5966
uint32_t GetIOHandlerID() const
Definition Process.h:2374
void SyncIOHandler(uint32_t iohandler_id, const Timeout< std::micro > &timeout)
Waits for the process state to be running within a given msec timeout.
Definition Process.cpp:648
uint32_t FindEntryIndexThatContains(B addr) const
Definition RangeMap.h:316
BaseType GetMaxRangeEnd(BaseType fail_value) const
Definition RangeMap.h:272
void Append(const Entry &entry)
Definition RangeMap.h:179
BaseType GetMinRangeBase(BaseType fail_value) const
Definition RangeMap.h:261
Process * GetProcess()
Definition Runtime.h:22
This base class provides an interface to stack frames.
Definition StackFrame.h:44
virtual const SymbolContext & GetSymbolContext(lldb::SymbolContextItem resolve_scope)
Provide a SymbolContext for this StackFrame's current pc value.
virtual bool HasDebugInformation()
Determine whether this StackFrame has debug information available or not.
virtual const Address & GetFrameCodeAddress()
Get an Address for the current pc value in this StackFrame.
An error handling class.
Definition Status.h:118
static Status FromErrorStringWithFormat(const char *format,...) __attribute__((format(printf
Definition Status.cpp:106
static Status FromErrorString(const char *str)
Definition Status.h:141
bool Fail() const
Test for error condition.
Definition Status.cpp:293
llvm::StringRef GetString() const
A stream class that can stream formatted output to a file.
Definition Stream.h:28
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
Definition Stream.cpp:132
size_t PutChar(char ch)
Definition Stream.cpp:129
Defines a symbol context baton that can be handed other debug core functions.
llvm::Error GetAddressRangeFromHereToEndLine(uint32_t end_line, AddressRange &range)
Function * function
The Function for a given query.
Block * block
The Block for a given query.
CompileUnit * comp_unit
The CompileUnit for a given query.
LineEntry line_entry
The LineEntry for a given query.
A plug-in interface definition class for system runtimes.
virtual lldb::ThreadSP GetExtendedBacktraceThread(lldb::ThreadSP thread, ConstString type)
Return a Thread which shows the origin of this thread's creation.
virtual const std::vector< ConstString > & GetExtendedBacktraceTypes()
Return a list of thread origin extended backtraces that may be available.
lldb::ExpressionResults EvaluateExpression(llvm::StringRef expression, ExecutionContextScope *exe_scope, lldb::ValueObjectSP &result_valobj_sp, const EvaluateExpressionOptions &options=EvaluateExpressionOptions(), std::string *fixed_expression=nullptr, ValueObject *ctx_obj=nullptr)
Definition Target.cpp:2836
uint32_t GetSize(bool can_update=true)
bool SetSelectedThreadByID(lldb::tid_t tid, bool notify=false)
lldb::ThreadSP FindThreadByIndexID(uint32_t index_id, bool can_update=true)
lldb::ThreadSP GetThreadAtIndex(uint32_t idx, bool can_update=true)
std::recursive_mutex & GetMutex() const override
lldb::ThreadSP FindThreadByID(lldb::tid_t tid, bool can_update=true)
Class used to dump the instructions of a TraceCursor using its current state and granularity.
Definition TraceDumper.h:51
std::optional< lldb::user_id_t > DumpInstructions(size_t count)
Dump count instructions of the thread trace starting at the current cursor position.
void DumpFunctionCalls()
Dump all function calls forwards chronologically and hierarchically.
A plug-in interface definition class for trace information.
Definition Trace.h:48
virtual lldb::CommandObjectSP GetThreadTraceStartCommand(CommandInterpreter &interpreter)=0
Get the command handle for the "thread trace start" command.
#define LLDB_OPT_SET_1
#define LLDB_OPT_SET_2
#define LLDB_INVALID_LINE_NUMBER
#define LLDB_INVALID_THREAD_ID
#define LLDB_INVALID_INDEX32
#define LLDB_OPT_SET_ALL
#define LLDB_INVALID_ADDRESS
#define UINT32_MAX
#define LLDB_INVALID_FRAME_ID
@ DoNoSelectMostRelevantFrame
A class that represents a running process on the host machine.
std::vector< OptionArgElement > OptionElementVector
Definition Options.h:43
const char * StateAsCString(lldb::StateType state)
Converts a StateType to a C string.
Definition State.cpp:14
std::string toString(FormatterBytecode::OpCodes op)
@ eStepTypeTraceOver
Single step one instruction, stepping over.
@ eStepTypeOut
Single step out a specified context.
@ eStepTypeScripted
A step type implemented by the script interpreter.
@ eStepTypeInto
Single step into a specified context.
@ eStepTypeOver
Single step over a specified context.
@ eStepTypeTrace
Single step one instruction.
@ eThreadIndexCompletion
std::shared_ptr< lldb_private::Trace > TraceSP
std::shared_ptr< lldb_private::ThreadPlan > ThreadPlanSP
std::shared_ptr< lldb_private::StackFrame > StackFrameSP
DescriptionLevel
Description levels for "void GetDescription(Stream *, DescriptionLevel)" calls.
@ eDescriptionLevelFull
@ eDescriptionLevelVerbose
std::shared_ptr< lldb_private::Thread > ThreadSP
std::shared_ptr< lldb_private::CommandObject > CommandObjectSP
std::shared_ptr< lldb_private::ValueObject > ValueObjectSP
StateType
Process and Thread States.
@ eStateStopped
Process or thread is stopped and can be examined.
@ eStateSuspended
Process or thread is in a suspended state as far as the debugger is concerned while other processes o...
@ eStateRunning
Process or thread is running and can't be examined.
@ eStateCrashed
Process or thread has crashed and can be examined.
ExpressionResults
The results of expression evaluation.
@ eExpressionCompleted
@ eExpressionSetupError
std::shared_ptr< lldb_private::Process > ProcessSP
@ eReturnStatusSuccessContinuingNoResult
@ eReturnStatusSuccessFinishResult
@ eReturnStatusSuccessFinishNoResult
@ eArgTypeThreadIndex
@ eArgTypeUnsignedInteger
@ eTraceCursorSeekTypeEnd
The end of the trace, i.e the most recent item.
std::shared_ptr< lldb_private::TraceCursor > TraceCursorSP
uint64_t addr_t
Definition lldb-types.h:80
std::shared_ptr< lldb_private::Target > TargetSP
RunMode
Thread Run Modes.
@ eOnlyDuringStepping
uint64_t tid_t
Definition lldb-types.h:84
std::shared_ptr< lldb_private::StackFrameList > StackFrameListSP
uint32_t frame_list_id_t
Definition lldb-types.h:86
Used to build individual command argument lists.
uint32_t arg_opt_set_association
This arg might be associated only with some particular option set(s).
A line table entry class.
Definition LineEntry.h:21
AddressRange range
The section offset address range for this line entry.
Definition LineEntry.h:137
uint32_t line
The source line number, or LLDB_INVALID_LINE_NUMBER if there is no line number information.
Definition LineEntry.h:151
const FileSpec & GetFile() const
Helper to access the file.
Definition LineEntry.h:134
static int64_t ToOptionEnum(llvm::StringRef s, const OptionEnumValues &enum_values, int32_t fail_value, Status &error)
static lldb::addr_t ToAddress(const ExecutionContext *exe_ctx, llvm::StringRef s, lldb::addr_t fail_value, Status *error_ptr)
Try to parse an address.
static bool ToBoolean(llvm::StringRef s, bool fail_value, bool *success_ptr)
Class that holds the configuration used by TraceDumper for traversing and dumping instructions.
Definition TraceDumper.h:21
lldb::user_id_t GetID() const
Get accessor for the user ID.
Definition UserID.h:47