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, tid);
306 return false;
307 }
308
309 Thread *thread = thread_sp.get();
310 Stream &strm = result.GetOutputStream();
311
312 // Check if provider filtering is requested.
313 if (m_options.m_provider_specific_backtrace) {
314 // Disallow 'bt --provider' from within a scripted frame provider.
315 // A provider's get_frame_at_index running 'bt --provider' would
316 // try to evaluate the very provider that is mid-construction,
317 // leading to infinite recursion.
318 if (thread->IsAnyProviderActive()) {
320 "cannot use '--provider' option while a scripted frame provider is "
321 "being constructed on this thread");
322 return false;
323 }
324
325 // Print thread status header, like regular bt. This also ensures the
326 // frame list is initialized and any providers are loaded.
327 thread->GetStatus(strm, /*start_frame=*/0, /*num_frames=*/0,
328 /*num_frames_with_source=*/0, /*stop_format=*/true,
329 /*show_hidden=*/false, /*only_stacks=*/false);
330
331 if (m_options.m_show_all_providers) {
332 // Show all providers: unwinder (0) through the last in the chain.
333 m_options.m_provider_start_id = 0;
334 const auto &chain = thread->GetProviderChainIds();
335 m_options.m_provider_end_id = chain.empty() ? 0 : chain.back().second;
336 }
337
338 // Provider filter mode: show sequential views for each provider in range.
339 bool first_provider = true;
340 for (lldb::frame_list_id_t provider_id = m_options.m_provider_start_id;
341 provider_id <= m_options.m_provider_end_id; ++provider_id) {
342
343 // Get the frame list for this provider.
344 lldb::StackFrameListSP frame_list_sp =
345 thread->GetFrameListByIdentifier(provider_id);
346
347 if (!frame_list_sp) {
348 // Provider doesn't exist - skip silently.
349 continue;
350 }
351
352 // Add blank line between providers for readability.
353 if (!first_provider)
354 strm.PutChar('\n');
355 first_provider = false;
356
357 // Print provider header.
358 strm.Printf("=== Provider %u", provider_id);
359
360 // Get provider metadata for header.
361 if (provider_id == 0) {
362 strm.PutCString(": Base Unwinder ===\n");
363 } else {
364 // Find the descriptor in the provider chain.
365 const auto &provider_chain = thread->GetProviderChainIds();
366 std::string provider_name = "Unknown";
367 std::string provider_desc;
368 std::optional<uint32_t> provider_priority;
369
370 for (const auto &[descriptor, id] : provider_chain) {
371 if (id == provider_id) {
372 provider_name = descriptor.GetName().str();
373 provider_desc = descriptor.GetDescription();
374 provider_priority = descriptor.GetPriority();
375 break;
376 }
377 }
378
379 strm.Printf(": %s", provider_name.c_str());
380 if (provider_priority.has_value()) {
381 strm.Printf(" (priority: %u)", *provider_priority);
382 }
383 strm.PutCString(" ===\n");
384
385 if (!provider_desc.empty()) {
386 strm.Printf("Description: %s\n", provider_desc.c_str());
387 }
388 }
389
390 // Print the backtrace for this provider.
391 const uint32_t num_frames_with_source = 0;
392 const StackFrameSP selected_frame_sp =
393 thread->GetSelectedFrame(DoNoSelectMostRelevantFrame);
394 const char *selected_frame_marker = selected_frame_sp ? "->" : nullptr;
395
396 size_t num_frames = frame_list_sp->GetStatus(
397 strm, m_options.m_start, m_options.m_count,
398 /*show_frame_info=*/true, num_frames_with_source,
399 /*show_unique=*/false,
400 /*show_hidden=*/!m_options.m_filtered_backtrace,
401 selected_frame_marker);
402
403 if (num_frames == 0) {
404 strm.PutCString("(No frames available)\n");
405 }
406 }
407
408 if (first_provider) {
409 result.AppendErrorWithFormat("no provider found in range %u-%u",
410 m_options.m_provider_start_id,
411 m_options.m_provider_end_id);
412 return false;
413 }
414 return true;
415 }
416
417 // Original behavior: show default backtrace.
418 const bool only_stacks = m_unique_stacks;
419 const uint32_t num_frames_with_source = 0;
420 const bool stop_format = true;
421 if (!thread->GetStatus(strm, m_options.m_start, m_options.m_count,
422 num_frames_with_source, stop_format,
423 !m_options.m_filtered_backtrace, only_stacks)) {
425 "error displaying backtrace for thread: \"0x%4.4x\"",
426 thread->GetIndexID());
427 return false;
428 }
429 if (m_options.m_extended_backtrace) {
431 "Interrupt skipped extended backtrace")) {
432 DoExtendedBacktrace(thread, result);
433 }
434 }
435
436 return true;
437 }
438
440};
441
442#define LLDB_OPTIONS_thread_step_scope
443#include "CommandOptions.inc"
444
446public:
448 // Keep default values of all options in one place: OptionParsingStarting
449 // ()
450 OptionParsingStarting(nullptr);
451 }
452
453 ~ThreadStepScopeOptionGroup() override = default;
454
455 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
456 return llvm::ArrayRef(g_thread_step_scope_options);
457 }
458
459 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
460 ExecutionContext *execution_context) override {
462 const int short_option =
463 g_thread_step_scope_options[option_idx].short_option;
464
465 switch (short_option) {
466 case 'a': {
467 bool success;
468 bool avoid_no_debug =
469 OptionArgParser::ToBoolean(option_arg, true, &success);
470 if (!success)
472 "invalid boolean value for option '%c': %s", short_option,
473 option_arg.data());
474 else {
476 }
477 } break;
478
479 case 'A': {
480 bool success;
481 bool avoid_no_debug =
482 OptionArgParser::ToBoolean(option_arg, true, &success);
483 if (!success)
485 "invalid boolean value for option '%c': %s", short_option,
486 option_arg.data());
487 else {
489 }
490 } break;
491
492 case 'c':
493 if (option_arg.getAsInteger(0, m_step_count))
495 "invalid integer value for option '%c': %s", short_option,
496 option_arg.data());
497 break;
498
499 case 'm': {
500 auto enum_values = GetDefinitions()[option_idx].enum_values;
502 option_arg, enum_values, eOnlyDuringStepping, error);
503 } break;
504
505 case 'e':
506 if (option_arg == "block") {
508 break;
509 }
510 if (option_arg.getAsInteger(0, m_end_line))
512 "invalid end line number '%s'", option_arg.str().c_str());
513 break;
514
515 case 'r':
516 m_avoid_regexp.clear();
517 m_avoid_regexp.assign(std::string(option_arg));
518 break;
519
520 case 't':
521 m_step_in_target.clear();
522 m_step_in_target.assign(std::string(option_arg));
523 break;
524
525 default:
526 llvm_unreachable("Unimplemented option");
527 }
528 return error;
529 }
530
531 void OptionParsingStarting(ExecutionContext *execution_context) override {
535
536 // Check if we are in Non-Stop mode
537 TargetSP target_sp =
538 execution_context ? execution_context->GetTargetSP() : TargetSP();
539 ProcessSP process_sp =
540 execution_context ? execution_context->GetProcessSP() : ProcessSP();
541 if (process_sp && process_sp->GetSteppingRunsAllThreads())
543
544 m_avoid_regexp.clear();
545 m_step_in_target.clear();
546 m_step_count = 1;
549 }
550
551 // Instance variables to hold the values for command options.
555 std::string m_avoid_regexp;
556 std::string m_step_in_target;
557 uint32_t m_step_count;
558 uint32_t m_end_line;
560};
561
563public:
565 const char *name, const char *help,
566 const char *syntax,
567 StepType step_type)
568 : CommandObjectParsed(interpreter, name, help, syntax,
569 eCommandRequiresProcess | eCommandRequiresThread |
570 eCommandTryTargetAPILock |
571 eCommandProcessMustBeLaunched |
572 eCommandProcessMustBePaused),
573 m_step_type(step_type), m_class_options("scripted step") {
575
576 if (step_type == eStepTypeScripted) {
579 }
580 m_all_options.Append(&m_options);
581 m_all_options.Finalize();
582 }
583
585
586 void
588 OptionElementVector &opt_element_vector) override {
589 if (request.GetCursorIndex())
590 return;
591 CommandObject::HandleArgumentCompletion(request, opt_element_vector);
592 }
593
594 Options *GetOptions() override { return &m_all_options; }
595
596protected:
597 void DoExecute(Args &command, CommandReturnObject &result) override {
598 Process *process = m_exe_ctx.GetProcessPtr();
599 bool synchronous_execution = m_interpreter.GetSynchronous();
600
601 const uint32_t num_threads = process->GetThreadList().GetSize();
602 Thread *thread = nullptr;
603
604 if (command.GetArgumentCount() == 0) {
605 thread = GetDefaultThread();
606
607 if (thread == nullptr) {
608 result.AppendError("no selected thread in process");
609 return;
610 }
611 } else {
612 const char *thread_idx_cstr = command.GetArgumentAtIndex(0);
613 uint32_t step_thread_idx;
614
615 if (!llvm::to_integer(thread_idx_cstr, step_thread_idx)) {
616 result.AppendErrorWithFormat("invalid thread index '%s'",
617 thread_idx_cstr);
618 return;
619 }
620 thread =
621 process->GetThreadList().FindThreadByIndexID(step_thread_idx).get();
622 if (thread == nullptr) {
624 "Thread index %u is out of range (valid values are 0 - %u)",
625 step_thread_idx, num_threads);
626 return;
627 }
628 }
629
631 if (m_class_options.GetName().empty()) {
632 result.AppendErrorWithFormat("empty class name for scripted step");
633 return;
634 } else if (!GetDebugger().GetScriptInterpreter()->CheckObjectExists(
635 m_class_options.GetName().c_str())) {
637 "class for scripted step: \"%s\" does not exist",
638 m_class_options.GetName().c_str());
639 return;
640 }
641 }
642
643 if (m_options.m_end_line != LLDB_INVALID_LINE_NUMBER &&
646 "end line option is only valid for step into");
647 return;
648 }
649
650 const bool abort_other_plans = false;
651 const lldb::RunMode stop_other_threads = m_options.m_run_mode;
652
653 // This is a bit unfortunate, but not all the commands in this command
654 // object support only while stepping, so I use the bool for them.
655 bool bool_stop_other_threads;
656 if (m_options.m_run_mode == eAllThreads)
657 bool_stop_other_threads = false;
658 else if (m_options.m_run_mode == eOnlyDuringStepping)
659 bool_stop_other_threads = (m_step_type != eStepTypeOut);
660 else
661 bool_stop_other_threads = true;
662
663 ThreadPlanSP new_plan_sp;
664 Status new_plan_status;
665
666 StackFrame *frame = thread->GetStackFrameAtIndex(0).get();
667 assert(frame != nullptr);
668
669 // First see if the frame has a custom step plan for us:
670 if (frame) {
671 llvm::Expected<lldb::ThreadPlanSP> frame_plan_result =
673 if (auto llvm_err = frame_plan_result.takeError()) {
675 "scripted frame provider got an error "
676 "while constructing step plan: \"%s\"",
677 llvm::toString(std::move(llvm_err)).c_str());
678 return;
679 }
680 new_plan_sp = *frame_plan_result;
681 }
682
683 if (new_plan_sp) {
684 thread->QueueThreadPlan(new_plan_sp, abort_other_plans);
685 new_plan_sp->SetStopOthers(bool_stop_other_threads);
686 } else {
687 if (m_step_type == eStepTypeInto) {
688 if (frame->HasDebugInformation()) {
689 AddressRange range;
690 SymbolContext sc = frame->GetSymbolContext(eSymbolContextEverything);
691 if (m_options.m_end_line != LLDB_INVALID_LINE_NUMBER) {
692 llvm::Error err = sc.GetAddressRangeFromHereToEndLine(
693 m_options.m_end_line, range);
694 if (err) {
695 result.AppendErrorWithFormatv("invalid end-line option: {0}.",
696 llvm::toString(std::move(err)));
697 return;
698 }
699 } else if (m_options.m_end_line_is_block_end) {
701 Block *block = frame->GetSymbolContext(eSymbolContextBlock).block;
702 if (!block) {
703 result.AppendErrorWithFormat("Could not find the current block");
704 return;
705 }
706
707 AddressRange block_range;
708 Address pc_address = frame->GetFrameCodeAddress();
709 block->GetRangeContainingAddress(pc_address, block_range);
710 if (!block_range.GetBaseAddress().IsValid()) {
712 "Could not find the current block address");
713 return;
714 }
715 lldb::addr_t pc_offset_in_block =
716 pc_address.GetFileAddress() -
717 block_range.GetBaseAddress().GetFileAddress();
718 lldb::addr_t range_length =
719 block_range.GetByteSize() - pc_offset_in_block;
720 range = AddressRange(pc_address, range_length);
721 } else {
722 range = sc.line_entry.range;
723 }
724
725 new_plan_sp = thread->QueueThreadPlanForStepInRange(
726 abort_other_plans, range,
727 frame->GetSymbolContext(eSymbolContextEverything),
728 m_options.m_step_in_target, stop_other_threads, new_plan_status,
729 m_options.m_step_in_avoid_no_debug,
730 m_options.m_step_out_avoid_no_debug);
731
732 if (new_plan_sp && !m_options.m_avoid_regexp.empty()) {
733 ThreadPlanStepInRange *step_in_range_plan =
734 static_cast<ThreadPlanStepInRange *>(new_plan_sp.get());
735 step_in_range_plan->SetAvoidRegexp(
736 m_options.m_avoid_regexp.c_str());
737 }
738 } else
739 new_plan_sp = thread->QueueThreadPlanForStepSingleInstruction(
740 false, abort_other_plans, bool_stop_other_threads,
741 new_plan_status);
742 } else if (m_step_type == eStepTypeOver) {
743
744 if (frame->HasDebugInformation())
745 new_plan_sp = thread->QueueThreadPlanForStepOverRange(
746 abort_other_plans,
747 frame->GetSymbolContext(eSymbolContextEverything).line_entry,
748 frame->GetSymbolContext(eSymbolContextEverything),
749 stop_other_threads, new_plan_status,
750 m_options.m_step_out_avoid_no_debug);
751 else
752 new_plan_sp = thread->QueueThreadPlanForStepSingleInstruction(
753 true, abort_other_plans, bool_stop_other_threads,
754 new_plan_status);
755 } else if (m_step_type == eStepTypeTrace) {
756 new_plan_sp = thread->QueueThreadPlanForStepSingleInstruction(
757 false, abort_other_plans, bool_stop_other_threads, new_plan_status);
758 } else if (m_step_type == eStepTypeTraceOver) {
759 new_plan_sp = thread->QueueThreadPlanForStepSingleInstruction(
760 true, abort_other_plans, bool_stop_other_threads, new_plan_status);
761 } else if (m_step_type == eStepTypeOut) {
762 new_plan_sp = thread->QueueThreadPlanForStepOut(
763 abort_other_plans, nullptr, false, bool_stop_other_threads,
765 thread->GetSelectedFrameIndex(DoNoSelectMostRelevantFrame),
766 new_plan_status, m_options.m_step_out_avoid_no_debug);
767 } else if (m_step_type == eStepTypeScripted) {
768 ScriptedMetadata scripted_metadata(m_class_options.GetName(),
769 m_class_options.GetStructuredData());
770 new_plan_sp = thread->QueueThreadPlanForStepScripted(
771 abort_other_plans, scripted_metadata, bool_stop_other_threads,
772 new_plan_status);
773 } else {
774 result.AppendError("step type is not supported");
775 return;
776 }
777 }
778
779 // If we got a new plan, then set it to be a controlling plan (User level
780 // Plans should be controlling plans so that they can be interruptible).
781 // Then resume the process.
782
783 if (new_plan_sp) {
784 new_plan_sp->SetIsControllingPlan(true);
785 new_plan_sp->SetOkayToDiscard(false);
786
787 if (m_options.m_step_count > 1) {
788 if (!new_plan_sp->SetIterationCount(m_options.m_step_count)) {
789 result.AppendWarning(
790 "step operation does not support iteration count");
791 }
792 }
793
794 process->GetThreadList().SetSelectedThreadByID(thread->GetID());
795
796 const uint32_t iohandler_id = process->GetIOHandlerID();
797
798 StreamString stream;
800 if (synchronous_execution)
801 error = process->ResumeSynchronous(&stream);
802 else
803 error = process->Resume();
804
805 if (!error.Success()) {
806 result.AppendMessage(error.AsCString());
808 return;
809 }
810
811 // There is a race condition where this thread will return up the call
812 // stack to the main command handler and show an (lldb) prompt before
813 // HandlePrivateEvent (from PrivateStateThread) has a chance to call
814 // PushProcessIOHandler().
815 process->SyncIOHandler(iohandler_id, std::chrono::seconds(2));
816
817 if (synchronous_execution) {
818 // If any state changed events had anything to say, add that to the
819 // result
820 if (stream.GetSize() > 0)
821 result.AppendMessage(stream.GetString());
822
823 process->GetThreadList().SetSelectedThreadByID(thread->GetID());
824 result.SetDidChangeProcessState(true);
826 } else {
828 }
829 } else {
830 result.SetError(std::move(new_plan_status));
831 }
832 }
833
838};
839
840// CommandObjectThreadContinue
841
843public:
846 interpreter, "thread continue",
847 "Continue execution of the current target process. One "
848 "or more threads may be specified, by default all "
849 "threads continue.",
850 nullptr,
851 eCommandRequiresThread | eCommandTryTargetAPILock |
852 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused) {
854 }
855
856 ~CommandObjectThreadContinue() override = default;
857
858 void DoExecute(Args &command, CommandReturnObject &result) override {
859 bool synchronous_execution = m_interpreter.GetSynchronous();
860
861 Process *process = m_exe_ctx.GetProcessPtr();
862 if (process == nullptr) {
863 result.AppendError("no process exists. Cannot continue");
864 return;
865 }
866
867 StateType state = process->GetState();
868 if ((state == eStateCrashed) || (state == eStateStopped) ||
869 (state == eStateSuspended)) {
870 const size_t argc = command.GetArgumentCount();
871 if (argc > 0) {
872 // These two lines appear at the beginning of both blocks in this
873 // if..else, but that is because we need to release the lock before
874 // calling process->Resume below.
875 std::lock_guard<std::recursive_mutex> guard(
876 process->GetThreadList().GetMutex());
877 const uint32_t num_threads = process->GetThreadList().GetSize();
878 std::vector<Thread *> resume_threads;
879 for (auto &entry : command.entries()) {
880 uint32_t thread_idx;
881 if (entry.ref().getAsInteger(0, thread_idx)) {
883 "invalid thread index argument: \"%s\"", entry.c_str());
884 return;
885 }
886 Thread *thread =
887 process->GetThreadList().FindThreadByIndexID(thread_idx).get();
888
889 if (thread) {
890 resume_threads.push_back(thread);
891 } else {
892 result.AppendErrorWithFormat("invalid thread index %u", thread_idx);
893 return;
894 }
895 }
896
897 if (resume_threads.empty()) {
898 result.AppendError("no valid thread indexes were specified");
899 return;
900 } else {
901 Stream &strm = result.GetOutputStream();
902 if (resume_threads.size() == 1)
903 strm << "Resuming thread: ";
904 else
905 strm << "Resuming threads: ";
906
907 for (uint32_t idx = 0; idx < num_threads; ++idx) {
908 Thread *thread =
909 process->GetThreadList().GetThreadAtIndex(idx).get();
910 std::vector<Thread *>::iterator this_thread_pos =
911 find(resume_threads.begin(), resume_threads.end(), thread);
912
913 if (this_thread_pos != resume_threads.end()) {
914 resume_threads.erase(this_thread_pos);
915 if (!resume_threads.empty())
916 strm << llvm::formatv("{0}, ", thread->GetIndexID());
917 else
918 strm << llvm::formatv("{0} ", thread->GetIndexID());
919
920 const bool override_suspend = true;
921 thread->SetResumeState(eStateRunning, override_suspend);
922 } else {
923 thread->SetResumeState(eStateSuspended);
924 }
925 }
926 result.AppendMessageWithFormatv("in process {0}", process->GetID());
927 }
928 } else {
929 // These two lines appear at the beginning of both blocks in this
930 // if..else, but that is because we need to release the lock before
931 // calling process->Resume below.
932 std::lock_guard<std::recursive_mutex> guard(
933 process->GetThreadList().GetMutex());
934 const uint32_t num_threads = process->GetThreadList().GetSize();
935 Thread *current_thread = GetDefaultThread();
936 if (current_thread == nullptr) {
937 result.AppendError("the process doesn't have a current thread");
938 return;
939 }
940 // Set the actions that the threads should each take when resuming
941 for (uint32_t idx = 0; idx < num_threads; ++idx) {
942 Thread *thread = process->GetThreadList().GetThreadAtIndex(idx).get();
943 if (thread == current_thread) {
945 "Resuming thread {0:x4} in process {1}", thread->GetID(),
946 process->GetID());
947 const bool override_suspend = true;
948 thread->SetResumeState(eStateRunning, override_suspend);
949 } else {
950 thread->SetResumeState(eStateSuspended);
951 }
952 }
953 }
954
955 StreamString stream;
957 if (synchronous_execution)
958 error = process->ResumeSynchronous(&stream);
959 else
960 error = process->Resume();
961
962 // We should not be holding the thread list lock when we do this.
963 if (error.Success()) {
964 result.AppendMessageWithFormatv("Process {0} resuming",
965 process->GetID());
966 if (synchronous_execution) {
967 // If any state changed events had anything to say, add that to the
968 // result
969 if (stream.GetSize() > 0)
970 result.AppendMessage(stream.GetString());
971
972 result.SetDidChangeProcessState(true);
974 } else {
976 }
977 } else {
978 result.AppendErrorWithFormat("Failed to resume process: %s",
979 error.AsCString());
980 }
981 } else {
983 "Process cannot be continued from its current state (%s)",
984 StateAsCString(state));
985 }
986 }
987};
988
989// CommandObjectThreadUntil
990
991#define LLDB_OPTIONS_thread_until
992#include "CommandOptions.inc"
993
995public:
996 class CommandOptions : public Options {
997 public:
1000
1002 // Keep default values of all options in one place: OptionParsingStarting
1003 // ()
1004 OptionParsingStarting(nullptr);
1005 }
1006
1007 ~CommandOptions() override = default;
1008
1009 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1010 ExecutionContext *execution_context) override {
1011 Status error;
1012 const int short_option = m_getopt_table[option_idx].val;
1013
1014 switch (short_option) {
1015 case 'a': {
1017 execution_context, option_arg, LLDB_INVALID_ADDRESS, &error);
1018 if (error.Success())
1019 m_until_addrs.push_back(tmp_addr);
1020 } break;
1021 case 't':
1022 if (option_arg.getAsInteger(0, m_thread_idx)) {
1024 error = Status::FromErrorStringWithFormat("invalid thread index '%s'",
1025 option_arg.str().c_str());
1026 }
1027 break;
1028 case 'f':
1029 if (option_arg.getAsInteger(0, m_frame_idx)) {
1031 error = Status::FromErrorStringWithFormat("invalid frame index '%s'",
1032 option_arg.str().c_str());
1033 }
1034 break;
1035 case 'm': {
1036 auto enum_values = GetDefinitions()[option_idx].enum_values;
1038 option_arg, enum_values, eOnlyDuringStepping, error);
1039
1040 if (error.Success()) {
1041 if (run_mode == eAllThreads)
1042 m_stop_others = false;
1043 else
1044 m_stop_others = true;
1045 }
1046 } break;
1047 default:
1048 llvm_unreachable("Unimplemented option");
1049 }
1050 return error;
1051 }
1052
1053 void OptionParsingStarting(ExecutionContext *execution_context) override {
1055 m_frame_idx = 0;
1056 m_stop_others = false;
1057 m_until_addrs.clear();
1058 }
1059
1060 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
1061 return llvm::ArrayRef(g_thread_until_options);
1062 }
1063
1064 bool m_stop_others = false;
1065 std::vector<lldb::addr_t> m_until_addrs;
1066
1067 // Instance variables to hold the values for command options.
1068 };
1069
1072 interpreter, "thread until",
1073 "Continue until a line number or address is reached by the "
1074 "current or specified thread. Stops when returning from "
1075 "the current function as a safety measure. "
1076 "The target line number(s) are given as arguments, and if more "
1077 "than one"
1078 " is provided, stepping will stop when the first one is hit.",
1079 nullptr,
1080 eCommandRequiresThread | eCommandTryTargetAPILock |
1081 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused) {
1083 }
1084
1085 ~CommandObjectThreadUntil() override = default;
1086
1087 Options *GetOptions() override { return &m_options; }
1088
1089protected:
1090 void DoExecute(Args &command, CommandReturnObject &result) override {
1091 bool synchronous_execution = m_interpreter.GetSynchronous();
1092
1093 Target *target = GetTarget();
1094
1095 Process *process = m_exe_ctx.GetProcessPtr();
1096 if (process == nullptr) {
1097 result.AppendError("need a valid process to step");
1098 } else {
1099 Thread *thread = nullptr;
1100 std::vector<uint32_t> line_numbers;
1101
1102 if (command.GetArgumentCount() >= 1) {
1103 size_t num_args = command.GetArgumentCount();
1104 for (size_t i = 0; i < num_args; i++) {
1105 uint32_t line_number;
1106 if (!llvm::to_integer(command.GetArgumentAtIndex(i), line_number)) {
1107 result.AppendErrorWithFormat("invalid line number: '%s'",
1108 command.GetArgumentAtIndex(i));
1109 return;
1110 } else
1111 line_numbers.push_back(line_number);
1112 }
1113 } else if (m_options.m_until_addrs.empty()) {
1114 result.AppendErrorWithFormat("No line number or address provided:\n%s",
1115 GetSyntax().str().c_str());
1116 return;
1117 }
1118
1119 if (m_options.m_thread_idx == LLDB_INVALID_THREAD_ID) {
1120 thread = GetDefaultThread();
1121 } else {
1122 thread = process->GetThreadList()
1123 .FindThreadByIndexID(m_options.m_thread_idx)
1124 .get();
1125 }
1126
1127 if (thread == nullptr) {
1128 const uint32_t num_threads = process->GetThreadList().GetSize();
1129 result.AppendErrorWithFormat(
1130 "Thread index %u is out of range (valid values are 0 - %u)",
1131 m_options.m_thread_idx, num_threads);
1132 return;
1133 }
1134
1135 const bool abort_other_plans = false;
1136
1137 StackFrame *frame =
1138 thread->GetStackFrameAtIndex(m_options.m_frame_idx).get();
1139 if (frame == nullptr) {
1140 result.AppendErrorWithFormat(
1141 "Frame index %u is out of range for thread id %" PRIu64,
1142 m_options.m_frame_idx, thread->GetID());
1143 return;
1144 }
1145
1146 ThreadPlanSP new_plan_sp;
1147 Status new_plan_status;
1148
1149 if (frame->HasDebugInformation()) {
1150 // Finally we got here... Translate the given line number to a bunch
1151 // of addresses:
1152 SymbolContext sc(frame->GetSymbolContext(eSymbolContextCompUnit));
1153 LineTable *line_table = nullptr;
1154 if (sc.comp_unit)
1155 line_table = sc.comp_unit->GetLineTable();
1156
1157 if (line_table == nullptr) {
1158 result.AppendErrorWithFormat("Failed to resolve the line table for "
1159 "frame %u of thread id %" PRIu64,
1160 m_options.m_frame_idx, thread->GetID());
1161 return;
1162 }
1163
1164 LineEntry function_start;
1165 std::vector<addr_t> address_list;
1166
1167 // Find the beginning & end index of the function, but first make
1168 // sure it is valid:
1169 if (!sc.function) {
1170 result.AppendErrorWithFormat("Have debug information but no "
1171 "function info - can't get until range");
1172 return;
1173 }
1174
1175 RangeVector<uint32_t, uint32_t> line_idx_ranges;
1176 for (const AddressRange &range : sc.function->GetAddressRanges()) {
1177 auto [begin, end] = line_table->GetLineEntryIndexRange(range);
1178 line_idx_ranges.Append(begin, end - begin);
1179 }
1180 line_idx_ranges.Sort();
1181
1182 bool found_something = false;
1183
1184 // Since not all source lines will contribute code, check if we are
1185 // setting the breakpoint on the exact line number or the nearest
1186 // subsequent line number and set breakpoints at all the line table
1187 // entries of the chosen line number (exact or nearest subsequent).
1188 for (uint32_t line_number : line_numbers) {
1189 LineEntry line_entry;
1190 bool exact = false;
1191 if (sc.comp_unit->FindLineEntry(0, line_number, nullptr, exact,
1192 &line_entry) == UINT32_MAX)
1193 continue;
1194
1195 found_something = true;
1196 line_number = line_entry.line;
1197 exact = true;
1198 uint32_t end_func_idx = line_idx_ranges.GetMaxRangeEnd(0);
1199 uint32_t idx = sc.comp_unit->FindLineEntry(
1200 line_idx_ranges.GetMinRangeBase(UINT32_MAX), line_number, nullptr,
1201 exact, &line_entry);
1202 while (idx < end_func_idx) {
1203 if (line_idx_ranges.FindEntryIndexThatContains(idx) != UINT32_MAX) {
1204 addr_t address =
1205 line_entry.range.GetBaseAddress().GetLoadAddress(target);
1206 if (address != LLDB_INVALID_ADDRESS)
1207 address_list.push_back(address);
1208 }
1209 idx = sc.comp_unit->FindLineEntry(idx + 1, line_number, nullptr,
1210 exact, &line_entry);
1211 }
1212 }
1213
1214 for (lldb::addr_t address : m_options.m_until_addrs) {
1215 AddressRange unused;
1216 if (sc.function->GetRangeContainingLoadAddress(address, *target,
1217 unused))
1218 address_list.push_back(address);
1219 }
1220
1221 if (address_list.empty()) {
1222 if (found_something)
1223 result.AppendErrorWithFormat(
1224 "Until target outside of the current function");
1225 else
1226 result.AppendErrorWithFormat(
1227 "No line entries matching until target");
1228
1229 return;
1230 }
1231
1232 new_plan_sp = thread->QueueThreadPlanForStepUntil(
1233 abort_other_plans, address_list, m_options.m_stop_others,
1234 m_options.m_frame_idx, new_plan_status);
1235 if (new_plan_sp) {
1236 // User level plans should be controlling plans so they can be
1237 // interrupted
1238 // (e.g. by hitting a breakpoint) and other plans executed by the
1239 // user (stepping around the breakpoint) and then a "continue" will
1240 // resume the original plan.
1241 new_plan_sp->SetIsControllingPlan(true);
1242 new_plan_sp->SetOkayToDiscard(false);
1243 } else {
1244 result.SetError(std::move(new_plan_status));
1245 return;
1246 }
1247 } else {
1248 result.AppendErrorWithFormat("Frame index %u of thread id %" PRIu64
1249 " has no debug information",
1250 m_options.m_frame_idx, thread->GetID());
1251 return;
1252 }
1253
1254 if (!process->GetThreadList().SetSelectedThreadByID(thread->GetID())) {
1255 result.AppendErrorWithFormat(
1256 "Failed to set the selected thread to thread id %" PRIu64,
1257 thread->GetID());
1258 return;
1259 }
1260
1261 StreamString stream;
1262 Status error;
1263 if (synchronous_execution)
1264 error = process->ResumeSynchronous(&stream);
1265 else
1266 error = process->Resume();
1267
1268 if (error.Success()) {
1269 result.AppendMessageWithFormatv("Process {0} resuming",
1270 process->GetID());
1271 if (synchronous_execution) {
1272 // If any state changed events had anything to say, add that to the
1273 // result
1274 if (stream.GetSize() > 0)
1275 result.AppendMessage(stream.GetString());
1276
1277 result.SetDidChangeProcessState(true);
1279 } else {
1281 }
1282 } else {
1283 result.AppendErrorWithFormat("Failed to resume process: %s",
1284 error.AsCString());
1285 }
1286 }
1287 }
1288
1290};
1291
1292// CommandObjectThreadSelect
1293
1294#define LLDB_OPTIONS_thread_select
1295#include "CommandOptions.inc"
1296
1298public:
1300 public:
1302
1303 ~OptionGroupThreadSelect() override = default;
1304
1305 void OptionParsingStarting(ExecutionContext *execution_context) override {
1307 }
1308
1309 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1310 ExecutionContext *execution_context) override {
1311 const int short_option = g_thread_select_options[option_idx].short_option;
1312 switch (short_option) {
1313 case 't': {
1314 if (option_arg.getAsInteger(0, m_thread_id)) {
1316 return Status::FromErrorStringWithFormat("Invalid thread ID: '%s'.",
1317 option_arg.str().c_str());
1318 }
1319 break;
1320 }
1321
1322 default:
1323 llvm_unreachable("Unimplemented option");
1324 }
1325
1326 return {};
1327 }
1328
1329 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
1330 return llvm::ArrayRef(g_thread_select_options);
1331 }
1332
1334 };
1335
1337 : CommandObjectParsed(interpreter, "thread select",
1338 "Change the currently selected thread.",
1339 "thread select <thread-index> (or -t <thread-id>)",
1340 eCommandRequiresProcess | eCommandTryTargetAPILock |
1341 eCommandProcessMustBeLaunched |
1342 eCommandProcessMustBePaused) {
1344 CommandArgumentData thread_idx_arg;
1345
1346 // Define the first (and only) variant of this arg.
1347 thread_idx_arg.arg_type = eArgTypeThreadIndex;
1348 thread_idx_arg.arg_repetition = eArgRepeatPlain;
1349 thread_idx_arg.arg_opt_set_association = LLDB_OPT_SET_1;
1350
1351 // There is only one variant this argument could be; put it into the
1352 // argument entry.
1353 arg.push_back(thread_idx_arg);
1354
1355 // Push the data for the first argument into the m_arguments vector.
1356 m_arguments.push_back(arg);
1357
1359 m_option_group.Finalize();
1360 }
1361
1362 ~CommandObjectThreadSelect() override = default;
1363
1364 void
1366 OptionElementVector &opt_element_vector) override {
1367 if (request.GetCursorIndex())
1368 return;
1369
1372 nullptr);
1373 }
1374
1375 Options *GetOptions() override { return &m_option_group; }
1376
1377protected:
1378 void DoExecute(Args &command, CommandReturnObject &result) override {
1379 Process *process = m_exe_ctx.GetProcessPtr();
1380 if (process == nullptr) {
1381 result.AppendError("no process");
1382 return;
1383 } else if (m_options.m_thread_id == LLDB_INVALID_THREAD_ID &&
1384 command.GetArgumentCount() != 1) {
1385 result.AppendErrorWithFormat(
1386 "'%s' takes exactly one thread index argument, or a thread ID "
1387 "option:\nUsage: %s",
1388 m_cmd_name.c_str(), m_cmd_syntax.c_str());
1389 return;
1390 } else if (m_options.m_thread_id != LLDB_INVALID_THREAD_ID &&
1391 command.GetArgumentCount() != 0) {
1392 result.AppendErrorWithFormat("'%s' cannot take both a thread ID option "
1393 "and a thread index argument:\nUsage: %s",
1394 m_cmd_name.c_str(), m_cmd_syntax.c_str());
1395 return;
1396 }
1397
1398 Thread *new_thread = nullptr;
1399 if (command.GetArgumentCount() == 1) {
1400 uint32_t index_id;
1401 if (!llvm::to_integer(command.GetArgumentAtIndex(0), index_id)) {
1402 result.AppendErrorWithFormat("Invalid thread index '%s'",
1403 command.GetArgumentAtIndex(0));
1404 return;
1405 }
1406 new_thread = process->GetThreadList().FindThreadByIndexID(index_id).get();
1407 if (new_thread == nullptr) {
1408 result.AppendErrorWithFormat("Invalid thread index #%s",
1409 command.GetArgumentAtIndex(0));
1410 return;
1411 }
1412 } else {
1413 new_thread =
1414 process->GetThreadList().FindThreadByID(m_options.m_thread_id).get();
1415 if (new_thread == nullptr) {
1416 result.AppendErrorWithFormat("Invalid thread ID %" PRIu64,
1417 m_options.m_thread_id);
1418 return;
1419 }
1420 }
1421
1422 process->GetThreadList().SetSelectedThreadByID(new_thread->GetID(), true);
1424 }
1425
1428};
1429
1430// CommandObjectThreadList
1431
1433public:
1436 interpreter, "thread list",
1437 "Show a summary of each thread in the current target process. "
1438 "Use 'settings set thread-format' to customize the individual "
1439 "thread listings.",
1440 "thread list",
1441 eCommandRequiresProcess | eCommandTryTargetAPILock |
1442 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused) {}
1443
1444 ~CommandObjectThreadList() override = default;
1445
1446protected:
1447 void DoExecute(Args &command, CommandReturnObject &result) override {
1448 Stream &strm = result.GetOutputStream();
1450 Process *process = m_exe_ctx.GetProcessPtr();
1451 const bool only_threads_with_stop_reason = false;
1452 const uint32_t start_frame = 0;
1453 const uint32_t num_frames = 0;
1454 const uint32_t num_frames_with_source = 0;
1455 process->GetStatus(strm);
1456 process->GetThreadStatus(strm, only_threads_with_stop_reason, start_frame,
1457 num_frames, num_frames_with_source, false);
1458 }
1459};
1460
1461// CommandObjectThreadInfo
1462#define LLDB_OPTIONS_thread_info
1463#include "CommandOptions.inc"
1464
1466public:
1467 class CommandOptions : public Options {
1468 public:
1470
1471 ~CommandOptions() override = default;
1472
1473 void OptionParsingStarting(ExecutionContext *execution_context) override {
1474 m_json_thread = false;
1475 m_json_stopinfo = false;
1476 m_backing_thread = false;
1477 }
1478
1479 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1480 ExecutionContext *execution_context) override {
1481 const int short_option = m_getopt_table[option_idx].val;
1482 Status error;
1483
1484 switch (short_option) {
1485 case 'j':
1486 m_json_thread = true;
1487 break;
1488
1489 case 's':
1490 m_json_stopinfo = true;
1491 break;
1492
1493 case 'b':
1494 m_backing_thread = true;
1495 break;
1496
1497 default:
1498 llvm_unreachable("Unimplemented option");
1499 }
1500 return error;
1501 }
1502
1503 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
1504 return llvm::ArrayRef(g_thread_info_options);
1505 }
1506
1510 };
1511
1514 interpreter, "thread info",
1515 "Show an extended summary of one or "
1516 "more threads. Defaults to the "
1517 "current thread.",
1518 "thread info",
1519 eCommandRequiresProcess | eCommandTryTargetAPILock |
1520 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused) {
1521 m_add_return = false;
1522 }
1523
1524 ~CommandObjectThreadInfo() override = default;
1525
1526 void
1533
1534 Options *GetOptions() override { return &m_options; }
1535
1537 ThreadSP thread_sp =
1538 m_exe_ctx.GetProcessPtr()->GetThreadList().FindThreadByID(tid);
1539 if (!thread_sp) {
1540 result.AppendErrorWithFormat("thread no longer exists: 0x%" PRIx64, tid);
1541 return false;
1542 }
1543
1544 Thread *thread = thread_sp.get();
1545 if (m_options.m_backing_thread && thread->GetBackingThread())
1546 thread = thread->GetBackingThread().get();
1547
1548 Stream &strm = result.GetOutputStream();
1549 if (!thread->GetDescription(strm, eDescriptionLevelFull,
1550 m_options.m_json_thread,
1551 m_options.m_json_stopinfo)) {
1552 result.AppendErrorWithFormat("error displaying info for thread: \"%d\"",
1553 thread->GetIndexID());
1554 return false;
1555 }
1556 return true;
1557 }
1558
1560};
1561
1562// CommandObjectThreadException
1563
1565public:
1568 interpreter, "thread exception",
1569 "Display the current exception object for a thread. Defaults to "
1570 "the current thread.",
1571 "thread exception",
1572 eCommandRequiresProcess | eCommandTryTargetAPILock |
1573 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused) {}
1574
1575 ~CommandObjectThreadException() override = default;
1576
1577 void
1584
1586 ThreadSP thread_sp =
1587 m_exe_ctx.GetProcessPtr()->GetThreadList().FindThreadByID(tid);
1588 if (!thread_sp) {
1589 result.AppendErrorWithFormat("thread no longer exists: 0x%" PRIx64, tid);
1590 return false;
1591 }
1592
1593 Stream &strm = result.GetOutputStream();
1594 ValueObjectSP exception_object_sp = thread_sp->GetCurrentException();
1595 if (exception_object_sp) {
1596 if (llvm::Error error = exception_object_sp->Dump(strm)) {
1597 result.AppendError(toString(std::move(error)));
1598 return false;
1599 }
1600 }
1601
1602 ThreadSP exception_thread_sp = thread_sp->GetCurrentExceptionBacktrace();
1603 if (exception_thread_sp && exception_thread_sp->IsValid()) {
1604 const uint32_t num_frames_with_source = 0;
1605 const bool stop_format = false;
1606 exception_thread_sp->GetStatus(strm, 0, UINT32_MAX,
1607 num_frames_with_source, stop_format,
1608 /*filtered*/ false);
1609 }
1610
1611 return true;
1612 }
1613};
1614
1616public:
1619 interpreter, "thread siginfo",
1620 "Display the current siginfo object for a thread. Defaults to "
1621 "the current thread.",
1622 "thread siginfo",
1623 eCommandRequiresProcess | eCommandTryTargetAPILock |
1624 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused) {}
1625
1626 ~CommandObjectThreadSiginfo() override = default;
1627
1628 void
1635
1637 ThreadSP thread_sp =
1638 m_exe_ctx.GetProcessPtr()->GetThreadList().FindThreadByID(tid);
1639 if (!thread_sp) {
1640 result.AppendErrorWithFormat("thread no longer exists: 0x%" PRIx64, tid);
1641 return false;
1642 }
1643
1644 Stream &strm = result.GetOutputStream();
1645 if (!thread_sp->GetDescription(strm, eDescriptionLevelFull, false, false)) {
1646 result.AppendErrorWithFormat("error displaying info for thread: \"%d\"",
1647 thread_sp->GetIndexID());
1648 return false;
1649 }
1650 ValueObjectSP exception_object_sp = thread_sp->GetSiginfoValue();
1651 if (exception_object_sp) {
1652 if (llvm::Error error = exception_object_sp->Dump(strm)) {
1653 result.AppendError(toString(std::move(error)));
1654 return false;
1655 }
1656 } else
1657 strm.PutCString("(no siginfo)\n");
1658 strm.PutChar('\n');
1659
1660 return true;
1661 }
1662};
1663
1664// CommandObjectThreadReturn
1665#define LLDB_OPTIONS_thread_return
1666#include "CommandOptions.inc"
1667
1669public:
1670 class CommandOptions : public Options {
1671 public:
1673 // Keep default values of all options in one place: OptionParsingStarting
1674 // ()
1675 OptionParsingStarting(nullptr);
1676 }
1677
1678 ~CommandOptions() override = default;
1679
1680 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1681 ExecutionContext *execution_context) override {
1682 Status error;
1683 const int short_option = m_getopt_table[option_idx].val;
1684
1685 switch (short_option) {
1686 case 'x': {
1687 bool success;
1688 bool tmp_value =
1689 OptionArgParser::ToBoolean(option_arg, false, &success);
1690 if (success)
1691 m_from_expression = tmp_value;
1692 else {
1694 "invalid boolean value '%s' for 'x' option",
1695 option_arg.str().c_str());
1696 }
1697 } break;
1698 default:
1699 llvm_unreachable("Unimplemented option");
1700 }
1701 return error;
1702 }
1703
1704 void OptionParsingStarting(ExecutionContext *execution_context) override {
1705 m_from_expression = false;
1706 }
1707
1708 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
1709 return llvm::ArrayRef(g_thread_return_options);
1710 }
1711
1712 bool m_from_expression = false;
1713
1714 // Instance variables to hold the values for command options.
1715 };
1716
1718 : CommandObjectRaw(interpreter, "thread return",
1719 "Prematurely return from a stack frame, "
1720 "short-circuiting execution of newer frames "
1721 "and optionally yielding a specified value. Defaults "
1722 "to the exiting the current stack "
1723 "frame.",
1724 "thread return",
1725 eCommandRequiresFrame | eCommandTryTargetAPILock |
1726 eCommandProcessMustBeLaunched |
1727 eCommandProcessMustBePaused) {
1729 }
1730
1731 ~CommandObjectThreadReturn() override = default;
1732
1733 Options *GetOptions() override { return &m_options; }
1734
1735protected:
1736 void DoExecute(llvm::StringRef command,
1737 CommandReturnObject &result) override {
1738 // I am going to handle this by hand, because I don't want you to have to
1739 // say:
1740 // "thread return -- -5".
1741 if (command.starts_with("-x")) {
1742 if (command.size() != 2U)
1743 result.AppendWarning("return values ignored when returning from user "
1744 "called expressions");
1745
1746 Thread *thread = m_exe_ctx.GetThreadPtr();
1747 Status error;
1748 error = thread->UnwindInnermostExpression();
1749 if (!error.Success()) {
1750 result.AppendErrorWithFormat("Unwinding expression failed - %s",
1751 error.AsCString());
1752 } else {
1753 bool success =
1754 thread->SetSelectedFrameByIndexNoisily(0, result.GetOutputStream());
1755 if (success) {
1756 m_exe_ctx.SetFrameSP(
1757 thread->GetSelectedFrame(DoNoSelectMostRelevantFrame));
1759 } else {
1760 result.AppendErrorWithFormat(
1761 "Could not select 0th frame after unwinding expression");
1762 }
1763 }
1764 return;
1765 }
1766
1767 ValueObjectSP return_valobj_sp;
1768
1769 StackFrameSP frame_sp = m_exe_ctx.GetFrameSP();
1770 uint32_t frame_idx = frame_sp->GetFrameIndex();
1771
1772 if (frame_sp->IsInlined()) {
1773 result.AppendError("don't know how to return from inlined frames");
1774 return;
1775 }
1776
1777 if (!command.empty()) {
1778 Target *target = m_exe_ctx.GetTargetPtr();
1780
1781 options.SetUnwindOnError(true);
1783
1785 exe_results = target->EvaluateExpression(command, frame_sp.get(),
1786 return_valobj_sp, options);
1787 if (exe_results != eExpressionCompleted) {
1788 if (return_valobj_sp)
1789 result.AppendErrorWithFormat(
1790 "Error evaluating result expression: %s",
1791 return_valobj_sp->GetError().AsCString());
1792 else
1793 result.AppendErrorWithFormat(
1794 "Unknown error evaluating result expression");
1795 return;
1796 }
1797 }
1798
1799 Status error;
1800 ThreadSP thread_sp = m_exe_ctx.GetThreadSP();
1801 const bool broadcast = true;
1802 error = thread_sp->ReturnFromFrame(frame_sp, return_valobj_sp, broadcast);
1803 if (!error.Success()) {
1804 result.AppendErrorWithFormat(
1805 "Error returning from frame %d of thread %d: %s", frame_idx,
1806 thread_sp->GetIndexID(), error.AsCString());
1807 return;
1808 }
1809
1811 }
1812
1814};
1815
1816// CommandObjectThreadJump
1817#define LLDB_OPTIONS_thread_jump
1818#include "CommandOptions.inc"
1819
1821public:
1822 class CommandOptions : public Options {
1823 public:
1825
1826 ~CommandOptions() override = default;
1827
1828 void OptionParsingStarting(ExecutionContext *execution_context) override {
1829 m_filenames.Clear();
1830 m_line_num = 0;
1831 m_line_offset = 0;
1833 m_force = false;
1834 }
1835
1836 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1837 ExecutionContext *execution_context) override {
1838 const int short_option = m_getopt_table[option_idx].val;
1839 Status error;
1840
1841 switch (short_option) {
1842 case 'f':
1843 m_filenames.AppendIfUnique(FileSpec(option_arg));
1844 if (m_filenames.GetSize() > 1)
1845 return Status::FromErrorString("only one source file expected.");
1846 break;
1847 case 'l':
1848 if (option_arg.getAsInteger(0, m_line_num))
1849 return Status::FromErrorStringWithFormat("invalid line number: '%s'.",
1850 option_arg.str().c_str());
1851 break;
1852 case 'b': {
1853 option_arg.consume_front("+");
1854
1855 if (option_arg.getAsInteger(0, m_line_offset))
1856 return Status::FromErrorStringWithFormat("invalid line offset: '%s'.",
1857 option_arg.str().c_str());
1858 break;
1859 }
1860 case 'a':
1861 m_load_addr = OptionArgParser::ToAddress(execution_context, option_arg,
1863 break;
1864 case 'r':
1865 m_force = true;
1866 break;
1867 default:
1868 llvm_unreachable("Unimplemented option");
1869 }
1870 return error;
1871 }
1872
1873 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
1874 return llvm::ArrayRef(g_thread_jump_options);
1875 }
1876
1878 uint32_t m_line_num;
1882 };
1883
1886 interpreter, "thread jump",
1887 "Sets the program counter to a new address.", "thread jump",
1888 eCommandRequiresFrame | eCommandTryTargetAPILock |
1889 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused) {}
1890
1891 ~CommandObjectThreadJump() override = default;
1892
1893 Options *GetOptions() override { return &m_options; }
1894
1895protected:
1896 void DoExecute(Args &args, CommandReturnObject &result) override {
1897 RegisterContext *reg_ctx = m_exe_ctx.GetRegisterContext();
1898 StackFrame *frame = m_exe_ctx.GetFramePtr();
1899 Thread *thread = m_exe_ctx.GetThreadPtr();
1900 Target *target = m_exe_ctx.GetTargetPtr();
1901 const SymbolContext &sym_ctx =
1902 frame->GetSymbolContext(eSymbolContextLineEntry);
1903
1904 if (m_options.m_load_addr != LLDB_INVALID_ADDRESS) {
1905 // Use this address directly.
1906 Address dest = Address(m_options.m_load_addr);
1907
1908 lldb::addr_t callAddr = dest.GetCallableLoadAddress(target);
1909 if (callAddr == LLDB_INVALID_ADDRESS) {
1910 result.AppendErrorWithFormat("Invalid destination address");
1911 return;
1912 }
1913
1914 if (!reg_ctx->SetPC(callAddr)) {
1915 result.AppendErrorWithFormat("Error changing PC value for thread %d",
1916 thread->GetIndexID());
1917 return;
1918 }
1919 } else {
1920 // Pick either the absolute line, or work out a relative one.
1921 int32_t line = (int32_t)m_options.m_line_num;
1922 if (line == 0)
1923 line = sym_ctx.line_entry.line + m_options.m_line_offset;
1924
1925 // Try the current file, but override if asked.
1926 FileSpec file = sym_ctx.line_entry.GetFile();
1927 if (m_options.m_filenames.GetSize() == 1)
1928 file = m_options.m_filenames.GetFileSpecAtIndex(0);
1929
1930 if (!file) {
1931 result.AppendErrorWithFormat(
1932 "no source file available for the current location");
1933 return;
1934 }
1935
1936 std::string warnings;
1937 Status err = thread->JumpToLine(file, line, m_options.m_force, &warnings);
1938
1939 if (err.Fail()) {
1940 result.SetError(std::move(err));
1941 return;
1942 }
1943
1944 if (!warnings.empty())
1945 result.AppendWarning(warnings.c_str());
1946 }
1947
1949 }
1950
1952};
1953
1954// Next are the subcommands of CommandObjectMultiwordThreadPlan
1955
1956// CommandObjectThreadPlanList
1957#define LLDB_OPTIONS_thread_plan_list
1958#include "CommandOptions.inc"
1959
1961public:
1962 class CommandOptions : public Options {
1963 public:
1965 // Keep default values of all options in one place: OptionParsingStarting
1966 // ()
1967 OptionParsingStarting(nullptr);
1968 }
1969
1970 ~CommandOptions() override = default;
1971
1972 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1973 ExecutionContext *execution_context) override {
1974 const int short_option = m_getopt_table[option_idx].val;
1975
1976 switch (short_option) {
1977 case 'i':
1978 m_internal = true;
1979 break;
1980 case 't':
1981 lldb::tid_t tid;
1982 if (option_arg.getAsInteger(0, tid))
1983 return Status::FromErrorStringWithFormat("invalid tid: '%s'.",
1984 option_arg.str().c_str());
1985 m_tids.push_back(tid);
1986 break;
1987 case 'u':
1988 m_unreported = false;
1989 break;
1990 case 'v':
1991 m_verbose = true;
1992 break;
1993 default:
1994 llvm_unreachable("Unimplemented option");
1995 }
1996 return {};
1997 }
1998
1999 void OptionParsingStarting(ExecutionContext *execution_context) override {
2000 m_verbose = false;
2001 m_internal = false;
2002 m_unreported = true; // The variable is "skip unreported" and we want to
2003 // skip unreported by default.
2004 m_tids.clear();
2005 }
2006
2007 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
2008 return llvm::ArrayRef(g_thread_plan_list_options);
2009 }
2010
2011 // Instance variables to hold the values for command options.
2015 std::vector<lldb::tid_t> m_tids;
2016 };
2017
2020 interpreter, "thread plan list",
2021 "Show thread plans for one or more threads. If no threads are "
2022 "specified, show the "
2023 "current thread. Use the thread-index \"all\" to see all threads.",
2024 nullptr,
2025 eCommandRequiresProcess | eCommandRequiresThread |
2026 eCommandTryTargetAPILock | eCommandProcessMustBeLaunched |
2027 eCommandProcessMustBePaused) {}
2028
2029 ~CommandObjectThreadPlanList() override = default;
2030
2031 Options *GetOptions() override { return &m_options; }
2032
2033 void DoExecute(Args &command, CommandReturnObject &result) override {
2034 // If we are reporting all threads, dispatch to the Process to do that:
2035 if (command.GetArgumentCount() == 0 && m_options.m_tids.empty()) {
2036 Stream &strm = result.GetOutputStream();
2037 DescriptionLevel desc_level = m_options.m_verbose
2040 m_exe_ctx.GetProcessPtr()->DumpThreadPlans(
2041 strm, desc_level, m_options.m_internal, true, m_options.m_unreported);
2043 return;
2044 } else {
2045 // Do any TID's that the user may have specified as TID, then do any
2046 // Thread Indexes...
2047 if (!m_options.m_tids.empty()) {
2048 Process *process = m_exe_ctx.GetProcessPtr();
2049 StreamString tmp_strm;
2050 for (lldb::tid_t tid : m_options.m_tids) {
2051 bool success = process->DumpThreadPlansForTID(
2052 tmp_strm, tid, eDescriptionLevelFull, m_options.m_internal,
2053 true /* condense_trivial */, m_options.m_unreported);
2054 // If we didn't find a TID, stop here and return an error.
2055 if (!success) {
2056 result.AppendError("Error dumping plans:");
2057 result.AppendError(tmp_strm.GetString());
2058 return;
2059 }
2060 // Otherwise, add our data to the output:
2061 result.GetOutputStream() << tmp_strm.GetString();
2062 }
2063 }
2064 return CommandObjectIterateOverThreads::DoExecute(command, result);
2065 }
2066 }
2067
2068protected:
2070 // If we have already handled this from a -t option, skip it here.
2071 if (llvm::is_contained(m_options.m_tids, tid))
2072 return true;
2073
2074 Process *process = m_exe_ctx.GetProcessPtr();
2075
2076 Stream &strm = result.GetOutputStream();
2078 if (m_options.m_verbose)
2079 desc_level = eDescriptionLevelVerbose;
2080
2081 process->DumpThreadPlansForTID(strm, tid, desc_level, m_options.m_internal,
2082 true /* condense_trivial */,
2083 m_options.m_unreported);
2084 return true;
2085 }
2086
2088};
2089
2091public:
2093 : CommandObjectParsed(interpreter, "thread plan discard",
2094 "Discards thread plans up to and including the "
2095 "specified index (see 'thread plan list'.) "
2096 "Only user visible plans can be discarded.",
2097 nullptr,
2098 eCommandRequiresProcess | eCommandRequiresThread |
2099 eCommandTryTargetAPILock |
2100 eCommandProcessMustBeLaunched |
2101 eCommandProcessMustBePaused) {
2103 }
2104
2106
2107 void
2109 OptionElementVector &opt_element_vector) override {
2110 if (!m_exe_ctx.HasThreadScope() || request.GetCursorIndex())
2111 return;
2112
2113 m_exe_ctx.GetThreadPtr()->AutoCompleteThreadPlans(request);
2114 }
2115
2116 void DoExecute(Args &args, CommandReturnObject &result) override {
2117 Thread *thread = m_exe_ctx.GetThreadPtr();
2118 if (args.GetArgumentCount() != 1) {
2119 result.AppendErrorWithFormat("Too many arguments, expected one - the "
2120 "thread plan index - but got %zu",
2121 args.GetArgumentCount());
2122 return;
2123 }
2124
2125 uint32_t thread_plan_idx;
2126 if (!llvm::to_integer(args.GetArgumentAtIndex(0), thread_plan_idx)) {
2127 result.AppendErrorWithFormat(
2128 "Invalid thread index: \"%s\" - should be unsigned int",
2129 args.GetArgumentAtIndex(0));
2130 return;
2131 }
2132
2133 if (thread_plan_idx == 0) {
2134 result.AppendErrorWithFormat(
2135 "You wouldn't really want me to discard the base thread plan");
2136 return;
2137 }
2138
2139 if (thread->DiscardUserThreadPlansUpToIndex(thread_plan_idx)) {
2141 } else {
2142 result.AppendErrorWithFormat(
2143 "Could not find User thread plan with index %s",
2144 args.GetArgumentAtIndex(0));
2145 }
2146 }
2147};
2148
2150public:
2152 : CommandObjectParsed(interpreter, "thread plan prune",
2153 "Removes any thread plans associated with "
2154 "currently unreported threads. "
2155 "Specify one or more TID's to remove, or if no "
2156 "TID's are provides, remove threads for all "
2157 "unreported threads",
2158 nullptr,
2159 eCommandRequiresProcess |
2160 eCommandTryTargetAPILock |
2161 eCommandProcessMustBeLaunched |
2162 eCommandProcessMustBePaused) {
2164 }
2165
2166 ~CommandObjectThreadPlanPrune() override = default;
2167
2168 void DoExecute(Args &args, CommandReturnObject &result) override {
2169 Process *process = m_exe_ctx.GetProcessPtr();
2170
2171 if (args.GetArgumentCount() == 0) {
2172 process->PruneThreadPlans();
2174 return;
2175 }
2176
2177 const size_t num_args = args.GetArgumentCount();
2178
2179 std::lock_guard<std::recursive_mutex> guard(
2180 process->GetThreadList().GetMutex());
2181
2182 for (size_t i = 0; i < num_args; i++) {
2183 lldb::tid_t tid;
2184 if (!llvm::to_integer(args.GetArgumentAtIndex(i), tid)) {
2185 result.AppendErrorWithFormat("invalid thread specification: \"%s\"",
2186 args.GetArgumentAtIndex(i));
2187 return;
2188 }
2189 if (!process->PruneThreadPlansForTID(tid)) {
2190 result.AppendErrorWithFormat("Could not find unreported tid: \"%s\"",
2191 args.GetArgumentAtIndex(i));
2192 return;
2193 }
2194 }
2196 }
2197};
2198
2199// CommandObjectMultiwordThreadPlan
2200
2202public:
2205 interpreter, "plan",
2206 "Commands for managing thread plans that control execution.",
2207 "thread plan <subcommand> [<subcommand objects]") {
2209 "list", CommandObjectSP(new CommandObjectThreadPlanList(interpreter)));
2211 "discard",
2214 "prune",
2216 }
2217
2219};
2220
2221// Next are the subcommands of CommandObjectMultiwordTrace
2222
2223// CommandObjectTraceExport
2224
2226public:
2229 interpreter, "trace thread export",
2230 "Commands for exporting traces of the threads in the current "
2231 "process to different formats.",
2232 "thread trace export <export-plugin> [<subcommand objects>]") {
2233
2234 for (auto &cbs : PluginManager::GetTraceExporterCallbacks()) {
2235 if (cbs.create_thread_trace_export_command)
2236 LoadSubCommand(cbs.name,
2237 cbs.create_thread_trace_export_command(interpreter));
2238 }
2239 }
2240};
2241
2242// CommandObjectTraceStart
2243
2245public:
2248 /*live_debug_session_only=*/true, interpreter, "thread trace start",
2249 "Start tracing threads with the corresponding trace "
2250 "plug-in for the current process.",
2251 "thread trace start [<trace-options>]") {}
2252
2253protected:
2257};
2258
2259// CommandObjectTraceStop
2260
2262public:
2265 interpreter, "thread trace stop",
2266 "Stop tracing threads, including the ones traced with the "
2267 "\"process trace start\" command."
2268 "Defaults to the current thread. Thread indices can be "
2269 "specified as arguments.\n Use the thread-index \"all\" to stop "
2270 "tracing "
2271 "for all existing threads.",
2272 "thread trace stop [<thread-index> <thread-index> ...]",
2273 eCommandRequiresProcess | eCommandTryTargetAPILock |
2274 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused |
2275 eCommandProcessMustBeTraced) {}
2276
2277 ~CommandObjectTraceStop() override = default;
2278
2280 llvm::ArrayRef<lldb::tid_t> tids) override {
2281 ProcessSP process_sp = m_exe_ctx.GetProcessSP();
2282
2283 TraceSP trace_sp = process_sp->GetTarget().GetTrace();
2284
2285 if (llvm::Error err = trace_sp->Stop(tids))
2286 result.AppendError(toString(std::move(err)));
2287 else
2289
2290 return result.Succeeded();
2291 }
2292};
2293
2295 CommandReturnObject &result) {
2296 if (args.GetArgumentCount() == 0)
2297 return exe_ctx.GetThreadSP();
2298
2299 const char *arg = args.GetArgumentAtIndex(0);
2300 uint32_t thread_idx;
2301
2302 if (!llvm::to_integer(arg, thread_idx)) {
2303 result.AppendErrorWithFormat("invalid thread specification: \"%s\"", arg);
2304 return nullptr;
2305 }
2306 ThreadSP thread_sp =
2307 exe_ctx.GetProcessRef().GetThreadList().FindThreadByIndexID(thread_idx);
2308 if (!thread_sp)
2309 result.AppendErrorWithFormat("no thread with index: \"%s\"", arg);
2310 return thread_sp;
2311}
2312
2313// CommandObjectTraceDumpFunctionCalls
2314#define LLDB_OPTIONS_thread_trace_dump_function_calls
2315#include "CommandOptions.inc"
2316
2318public:
2319 class CommandOptions : public Options {
2320 public:
2322
2323 ~CommandOptions() override = default;
2324
2325 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
2326 ExecutionContext *execution_context) override {
2327 Status error;
2328 const int short_option = m_getopt_table[option_idx].val;
2329
2330 switch (short_option) {
2331 case 'j': {
2332 m_dumper_options.json = true;
2333 break;
2334 }
2335 case 'J': {
2336 m_dumper_options.json = true;
2337 m_dumper_options.pretty_print_json = true;
2338 break;
2339 }
2340 case 'F': {
2341 m_output_file.emplace(option_arg);
2342 break;
2343 }
2344 default:
2345 llvm_unreachable("Unimplemented option");
2346 }
2347 return error;
2348 }
2349
2350 void OptionParsingStarting(ExecutionContext *execution_context) override {
2351 m_dumper_options = {};
2352 m_output_file = std::nullopt;
2353 }
2354
2355 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
2356 return llvm::ArrayRef(g_thread_trace_dump_function_calls_options);
2357 }
2358
2359 static const size_t kDefaultCount = 20;
2360
2361 // Instance variables to hold the values for command options.
2363 std::optional<FileSpec> m_output_file;
2364 };
2365
2368 interpreter, "thread trace dump function-calls",
2369 "Dump the traced function-calls for one thread. If no "
2370 "thread is specified, the current thread is used.",
2371 nullptr,
2372 eCommandRequiresProcess | eCommandRequiresThread |
2373 eCommandTryTargetAPILock | eCommandProcessMustBeLaunched |
2374 eCommandProcessMustBePaused | eCommandProcessMustBeTraced) {
2376 }
2377
2379
2380 Options *GetOptions() override { return &m_options; }
2381
2382protected:
2383 void DoExecute(Args &args, CommandReturnObject &result) override {
2384 ThreadSP thread_sp = GetSingleThreadFromArgs(m_exe_ctx, args, result);
2385 if (!thread_sp) {
2386 result.AppendError("invalid thread\n");
2387 return;
2388 }
2389
2390 llvm::Expected<TraceCursorSP> cursor_or_error =
2391 m_exe_ctx.GetTargetSP()->GetTrace()->CreateNewCursor(*thread_sp);
2392
2393 if (!cursor_or_error) {
2394 result.AppendError(llvm::toString(cursor_or_error.takeError()));
2395 return;
2396 }
2397 TraceCursorSP &cursor_sp = *cursor_or_error;
2398
2399 std::optional<StreamFile> out_file;
2400 if (m_options.m_output_file) {
2401 out_file.emplace(m_options.m_output_file->GetPath().c_str(),
2404 }
2405
2406 m_options.m_dumper_options.forwards = true;
2407
2408 TraceDumper dumper(std::move(cursor_sp),
2409 out_file ? *out_file : result.GetOutputStream(),
2410 m_options.m_dumper_options);
2411
2412 dumper.DumpFunctionCalls();
2413 }
2414
2416};
2417
2418// CommandObjectTraceDumpInstructions
2419#define LLDB_OPTIONS_thread_trace_dump_instructions
2420#include "CommandOptions.inc"
2421
2423public:
2424 class CommandOptions : public Options {
2425 public:
2427
2428 ~CommandOptions() override = default;
2429
2430 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
2431 ExecutionContext *execution_context) override {
2432 Status error;
2433 const int short_option = m_getopt_table[option_idx].val;
2434
2435 switch (short_option) {
2436 case 'c': {
2437 int32_t count;
2438 if (option_arg.empty() || option_arg.getAsInteger(0, count) ||
2439 count < 0)
2441 "invalid integer value for option '%s'",
2442 option_arg.str().c_str());
2443 else
2444 m_count = count;
2445 break;
2446 }
2447 case 'a': {
2448 m_count = std::numeric_limits<decltype(m_count)>::max();
2449 break;
2450 }
2451 case 's': {
2452 int32_t skip;
2453 if (option_arg.empty() || option_arg.getAsInteger(0, skip) || skip < 0)
2455 "invalid integer value for option '%s'",
2456 option_arg.str().c_str());
2457 else
2458 m_dumper_options.skip = skip;
2459 break;
2460 }
2461 case 'i': {
2462 uint64_t id;
2463 if (option_arg.empty() || option_arg.getAsInteger(0, id))
2465 "invalid integer value for option '%s'",
2466 option_arg.str().c_str());
2467 else
2468 m_dumper_options.id = id;
2469 break;
2470 }
2471 case 'F': {
2472 m_output_file.emplace(option_arg);
2473 break;
2474 }
2475 case 'r': {
2476 m_dumper_options.raw = true;
2477 break;
2478 }
2479 case 'f': {
2480 m_dumper_options.forwards = true;
2481 break;
2482 }
2483 case 'k': {
2484 m_dumper_options.show_control_flow_kind = true;
2485 break;
2486 }
2487 case 't': {
2488 m_dumper_options.show_timestamps = true;
2489 break;
2490 }
2491 case 'e': {
2492 m_dumper_options.show_events = true;
2493 break;
2494 }
2495 case 'j': {
2496 m_dumper_options.json = true;
2497 break;
2498 }
2499 case 'J': {
2500 m_dumper_options.pretty_print_json = true;
2501 m_dumper_options.json = true;
2502 break;
2503 }
2504 case 'E': {
2505 m_dumper_options.only_events = true;
2506 m_dumper_options.show_events = true;
2507 break;
2508 }
2509 case 'C': {
2510 m_continue = true;
2511 break;
2512 }
2513 default:
2514 llvm_unreachable("Unimplemented option");
2515 }
2516 return error;
2517 }
2518
2519 void OptionParsingStarting(ExecutionContext *execution_context) override {
2521 m_continue = false;
2522 m_output_file = std::nullopt;
2523 m_dumper_options = {};
2524 }
2525
2526 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
2527 return llvm::ArrayRef(g_thread_trace_dump_instructions_options);
2528 }
2529
2530 static const size_t kDefaultCount = 20;
2531
2532 // Instance variables to hold the values for command options.
2533 size_t m_count;
2535 std::optional<FileSpec> m_output_file;
2537 };
2538
2541 interpreter, "thread trace dump instructions",
2542 "Dump the traced instructions for one thread. If no "
2543 "thread is specified, show the current thread.",
2544 nullptr,
2545 eCommandRequiresProcess | eCommandRequiresThread |
2546 eCommandTryTargetAPILock | eCommandProcessMustBeLaunched |
2547 eCommandProcessMustBePaused | eCommandProcessMustBeTraced) {
2549 }
2550
2552
2553 Options *GetOptions() override { return &m_options; }
2554
2555 std::optional<std::string> GetRepeatCommand(Args &current_command_args,
2556 uint32_t index) override {
2557 std::string cmd;
2558 current_command_args.GetCommandString(cmd);
2559 if (cmd.find(" --continue") == std::string::npos)
2560 cmd += " --continue";
2561 return cmd;
2562 }
2563
2564protected:
2565 void DoExecute(Args &args, CommandReturnObject &result) override {
2566 ThreadSP thread_sp = GetSingleThreadFromArgs(m_exe_ctx, args, result);
2567 if (!thread_sp) {
2568 result.AppendError("invalid thread\n");
2569 return;
2570 }
2571
2572 if (m_options.m_continue && m_last_id) {
2573 // We set up the options to continue one instruction past where
2574 // the previous iteration stopped.
2575 m_options.m_dumper_options.skip = 1;
2576 m_options.m_dumper_options.id = m_last_id;
2577 }
2578
2579 llvm::Expected<TraceCursorSP> cursor_or_error =
2580 m_exe_ctx.GetTargetSP()->GetTrace()->CreateNewCursor(*thread_sp);
2581
2582 if (!cursor_or_error) {
2583 result.AppendError(llvm::toString(cursor_or_error.takeError()));
2584 return;
2585 }
2586 TraceCursorSP &cursor_sp = *cursor_or_error;
2587
2588 if (m_options.m_dumper_options.id &&
2589 !cursor_sp->HasId(*m_options.m_dumper_options.id)) {
2590 result.AppendError("invalid instruction id\n");
2591 return;
2592 }
2593
2594 std::optional<StreamFile> out_file;
2595 if (m_options.m_output_file) {
2596 out_file.emplace(m_options.m_output_file->GetPath().c_str(),
2599 }
2600
2601 if (m_options.m_continue && !m_last_id) {
2602 // We need to stop processing data when we already ran out of instructions
2603 // in a previous command. We can fake this by setting the cursor past the
2604 // end of the trace.
2605 cursor_sp->Seek(1, lldb::eTraceCursorSeekTypeEnd);
2606 }
2607
2608 TraceDumper dumper(std::move(cursor_sp),
2609 out_file ? *out_file : result.GetOutputStream(),
2610 m_options.m_dumper_options);
2611
2612 m_last_id = dumper.DumpInstructions(m_options.m_count);
2613 }
2614
2616 // Last traversed id used to continue a repeat command. std::nullopt means
2617 // that all the trace has been consumed.
2618 std::optional<lldb::user_id_t> m_last_id;
2619};
2620
2621// CommandObjectTraceDumpInfo
2622#define LLDB_OPTIONS_thread_trace_dump_info
2623#include "CommandOptions.inc"
2624
2626public:
2627 class CommandOptions : public Options {
2628 public:
2630
2631 ~CommandOptions() override = default;
2632
2633 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
2634 ExecutionContext *execution_context) override {
2635 Status error;
2636 const int short_option = m_getopt_table[option_idx].val;
2637
2638 switch (short_option) {
2639 case 'v': {
2640 m_verbose = true;
2641 break;
2642 }
2643 case 'j': {
2644 m_json = true;
2645 break;
2646 }
2647 default:
2648 llvm_unreachable("Unimplemented option");
2649 }
2650 return error;
2651 }
2652
2653 void OptionParsingStarting(ExecutionContext *execution_context) override {
2654 m_verbose = false;
2655 m_json = false;
2656 }
2657
2658 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
2659 return llvm::ArrayRef(g_thread_trace_dump_info_options);
2660 }
2661
2662 // Instance variables to hold the values for command options.
2665 };
2666
2669 interpreter, "thread trace dump info",
2670 "Dump the traced information for one or more threads. If no "
2671 "threads are specified, show the current thread. Use the "
2672 "thread-index \"all\" to see all threads.",
2673 nullptr,
2674 eCommandRequiresProcess | eCommandTryTargetAPILock |
2675 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused |
2676 eCommandProcessMustBeTraced) {}
2677
2678 ~CommandObjectTraceDumpInfo() override = default;
2679
2680 Options *GetOptions() override { return &m_options; }
2681
2682protected:
2684 const TraceSP &trace_sp = m_exe_ctx.GetTargetSP()->GetTrace();
2685 ThreadSP thread_sp =
2686 m_exe_ctx.GetProcessPtr()->GetThreadList().FindThreadByID(tid);
2687 trace_sp->DumpTraceInfo(*thread_sp, result.GetOutputStream(),
2688 m_options.m_verbose, m_options.m_json);
2689 return true;
2690 }
2691
2693};
2694
2695// CommandObjectMultiwordTraceDump
2697public:
2700 interpreter, "dump",
2701 "Commands for displaying trace information of the threads "
2702 "in the current process.",
2703 "thread trace dump <subcommand> [<subcommand objects>]") {
2705 "instructions",
2708 "function-calls",
2711 "info", CommandObjectSP(new CommandObjectTraceDumpInfo(interpreter)));
2712 }
2714};
2715
2716// CommandObjectMultiwordTrace
2718public:
2721 interpreter, "trace",
2722 "Commands for operating on traces of the threads in the current "
2723 "process.",
2724 "thread trace <subcommand> [<subcommand objects>]") {
2726 interpreter)));
2727 LoadSubCommand("start",
2728 CommandObjectSP(new CommandObjectTraceStart(interpreter)));
2729 LoadSubCommand("stop",
2730 CommandObjectSP(new CommandObjectTraceStop(interpreter)));
2731 LoadSubCommand("export",
2732 CommandObjectSP(new CommandObjectTraceExport(interpreter)));
2733 }
2734
2735 ~CommandObjectMultiwordTrace() override = default;
2736};
2737
2738// CommandObjectMultiwordThread
2739
2741 CommandInterpreter &interpreter)
2742 : CommandObjectMultiword(interpreter, "thread",
2743 "Commands for operating on "
2744 "one or more threads in "
2745 "the current process.",
2746 "thread <subcommand> [<subcommand-options>]") {
2748 interpreter)));
2749 LoadSubCommand("continue",
2751 LoadSubCommand("list",
2752 CommandObjectSP(new CommandObjectThreadList(interpreter)));
2753 LoadSubCommand("return",
2754 CommandObjectSP(new CommandObjectThreadReturn(interpreter)));
2755 LoadSubCommand("jump",
2756 CommandObjectSP(new CommandObjectThreadJump(interpreter)));
2757 LoadSubCommand("select",
2758 CommandObjectSP(new CommandObjectThreadSelect(interpreter)));
2759 LoadSubCommand("until",
2760 CommandObjectSP(new CommandObjectThreadUntil(interpreter)));
2761 LoadSubCommand("info",
2762 CommandObjectSP(new CommandObjectThreadInfo(interpreter)));
2764 interpreter)));
2765 LoadSubCommand("siginfo",
2767 LoadSubCommand("step-in",
2769 interpreter, "thread step-in",
2770 "Source level single step, stepping into calls. Defaults "
2771 "to current thread unless specified.",
2772 nullptr, eStepTypeInto)));
2773
2774 LoadSubCommand("step-out",
2776 interpreter, "thread step-out",
2777 "Finish executing the current stack frame and stop after "
2778 "returning. Defaults to current thread unless specified.",
2779 nullptr, eStepTypeOut)));
2780
2781 LoadSubCommand("step-over",
2783 interpreter, "thread step-over",
2784 "Source level single step, stepping over calls. Defaults "
2785 "to current thread unless specified.",
2786 nullptr, eStepTypeOver)));
2787
2788 LoadSubCommand("step-inst",
2790 interpreter, "thread step-inst",
2791 "Instruction level single step, stepping into calls. "
2792 "Defaults to current thread unless specified.",
2793 nullptr, eStepTypeTrace)));
2794
2795 LoadSubCommand("step-inst-over",
2797 interpreter, "thread step-inst-over",
2798 "Instruction level single step, stepping over calls. "
2799 "Defaults to current thread unless specified.",
2800 nullptr, eStepTypeTraceOver)));
2801
2803 "step-scripted",
2805 interpreter, "thread step-scripted",
2806 "Step as instructed by the script class passed in the -C option. "
2807 "You can also specify a dictionary of key (-k) and value (-v) pairs "
2808 "that will be used to populate an SBStructuredData Dictionary, which "
2809 "will be passed to the constructor of the class implementing the "
2810 "scripted step. See the Python Reference for more details.",
2811 nullptr, eStepTypeScripted)));
2812
2814 interpreter)));
2815 LoadSubCommand("trace",
2817}
2818
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:502
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:303
lldb::addr_t GetCallableLoadAddress(Target *target, bool is_indirect=false) const
Get the load address as a callable code load address.
Definition Address.cpp:328
lldb::addr_t GetFileAddress() const
Get the file address.
Definition Address.cpp:283
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,...
Target * GetTarget()
Get the target this command should operate on.
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:406
void SetUseDynamic(lldb::DynamicValueType dynamic=lldb::eDynamicCanRunTarget)
Definition Target.h:421
"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:56
bool GetRangeContainingLoadAddress(lldb::addr_t load_addr, Target &target, AddressRange &range)
Definition Function.h:441
AddressRanges GetAddressRanges()
Definition Function.h:434
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:367
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:551
ThreadList & GetThreadList()
Definition Process.h:2408
Status Resume()
Resumes all of a process's threads as configured using the Thread run control functions.
Definition Process.cpp:1355
void PruneThreadPlans()
Prune ThreadPlanStacks for all unreported threads.
Definition Process.cpp:1240
bool PruneThreadPlansForTID(lldb::tid_t tid)
Prune ThreadPlanStacks for unreported threads.
Definition Process.cpp:1236
virtual SystemRuntime * GetSystemRuntime()
Get the system runtime plug-in for this process.
Definition Process.cpp:3178
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:1244
Status ResumeSynchronous(Stream *stream)
Resume a process, and wait for it to stop.
Definition Process.cpp:1372
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:6119
lldb::StateType GetState()
Get accessor for the current process state.
Definition Process.cpp:1296
uint32_t GetIOHandlerID() const
Definition Process.h:2470
void GetStatus(Stream &ostrm, bool is_verbose=false)
Definition Process.cpp:6096
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:685
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 llvm::Expected< lldb::ThreadPlanSP > GetThreadPlanForStepType(lldb::StepType step_type)
Definition StackFrame.h:570
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:134
size_t PutCString(llvm::StringRef cstr)
Output a C string to the stream.
Definition Stream.cpp:63
size_t PutChar(char ch)
Definition Stream.cpp:131
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:2951
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)
@ 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
@ eReturnStatusFailed
@ eReturnStatusSuccessContinuingNoResult
@ eReturnStatusSuccessFinishResult
@ eReturnStatusSuccessFinishNoResult
@ eArgTypeThreadIndex
@ eArgTypeUnsignedInteger
@ eTraceCursorSeekTypeEnd
The end of the trace, i.e the most recent item.
std::shared_ptr< lldb_private::TraceCursor > TraceCursorSP
@ eStepTypeInto
Single step into a specified context.
@ eStepTypeTraceOver
Single step one instruction, stepping over.
@ eStepTypeTrace
Single step one instruction.
@ eStepTypeOut
Single step out a specified context.
@ eStepTypeScripted
A step type implemented by the script interpreter.
@ eStepTypeOver
Single step over a specified context.
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:85
std::shared_ptr< lldb_private::StackFrameList > StackFrameListSP
uint32_t frame_list_id_t
Definition lldb-types.h:87
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