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.Printf(": 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.Printf(" ===\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.Printf("(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 if (m_step_type == eStepTypeInto) {
667 StackFrame *frame = thread->GetStackFrameAtIndex(0).get();
668 assert(frame != nullptr);
669
670 if (frame->HasDebugInformation()) {
671 AddressRange range;
672 SymbolContext sc = frame->GetSymbolContext(eSymbolContextEverything);
673 if (m_options.m_end_line != LLDB_INVALID_LINE_NUMBER) {
674 llvm::Error err =
675 sc.GetAddressRangeFromHereToEndLine(m_options.m_end_line, range);
676 if (err) {
677 result.AppendErrorWithFormatv("invalid end-line option: {0}.",
678 llvm::toString(std::move(err)));
679 return;
680 }
681 } else if (m_options.m_end_line_is_block_end) {
683 Block *block = frame->GetSymbolContext(eSymbolContextBlock).block;
684 if (!block) {
685 result.AppendErrorWithFormat("Could not find the current block");
686 return;
687 }
688
689 AddressRange block_range;
690 Address pc_address = frame->GetFrameCodeAddress();
691 block->GetRangeContainingAddress(pc_address, block_range);
692 if (!block_range.GetBaseAddress().IsValid()) {
694 "Could not find the current block address");
695 return;
696 }
697 lldb::addr_t pc_offset_in_block =
698 pc_address.GetFileAddress() -
699 block_range.GetBaseAddress().GetFileAddress();
700 lldb::addr_t range_length =
701 block_range.GetByteSize() - pc_offset_in_block;
702 range = AddressRange(pc_address, range_length);
703 } else {
704 range = sc.line_entry.range;
705 }
706
707 new_plan_sp = thread->QueueThreadPlanForStepInRange(
708 abort_other_plans, range,
709 frame->GetSymbolContext(eSymbolContextEverything),
710 m_options.m_step_in_target.c_str(), stop_other_threads,
711 new_plan_status, m_options.m_step_in_avoid_no_debug,
712 m_options.m_step_out_avoid_no_debug);
713
714 if (new_plan_sp && !m_options.m_avoid_regexp.empty()) {
715 ThreadPlanStepInRange *step_in_range_plan =
716 static_cast<ThreadPlanStepInRange *>(new_plan_sp.get());
717 step_in_range_plan->SetAvoidRegexp(m_options.m_avoid_regexp.c_str());
718 }
719 } else
720 new_plan_sp = thread->QueueThreadPlanForStepSingleInstruction(
721 false, abort_other_plans, bool_stop_other_threads, new_plan_status);
722 } else if (m_step_type == eStepTypeOver) {
723 StackFrame *frame = thread->GetStackFrameAtIndex(0).get();
724
725 if (frame->HasDebugInformation())
726 new_plan_sp = thread->QueueThreadPlanForStepOverRange(
727 abort_other_plans,
728 frame->GetSymbolContext(eSymbolContextEverything).line_entry,
729 frame->GetSymbolContext(eSymbolContextEverything),
730 stop_other_threads, new_plan_status,
731 m_options.m_step_out_avoid_no_debug);
732 else
733 new_plan_sp = thread->QueueThreadPlanForStepSingleInstruction(
734 true, abort_other_plans, bool_stop_other_threads, new_plan_status);
735 } else if (m_step_type == eStepTypeTrace) {
736 new_plan_sp = thread->QueueThreadPlanForStepSingleInstruction(
737 false, abort_other_plans, bool_stop_other_threads, new_plan_status);
738 } else if (m_step_type == eStepTypeTraceOver) {
739 new_plan_sp = thread->QueueThreadPlanForStepSingleInstruction(
740 true, abort_other_plans, bool_stop_other_threads, new_plan_status);
741 } else if (m_step_type == eStepTypeOut) {
742 new_plan_sp = thread->QueueThreadPlanForStepOut(
743 abort_other_plans, nullptr, false, bool_stop_other_threads, eVoteYes,
745 thread->GetSelectedFrameIndex(DoNoSelectMostRelevantFrame),
746 new_plan_status, m_options.m_step_out_avoid_no_debug);
747 } else if (m_step_type == eStepTypeScripted) {
748 ScriptedMetadata scripted_metadata(m_class_options.GetName(),
749 m_class_options.GetStructuredData());
750 new_plan_sp = thread->QueueThreadPlanForStepScripted(
751 abort_other_plans, scripted_metadata, bool_stop_other_threads,
752 new_plan_status);
753 } else {
754 result.AppendError("step type is not supported");
755 return;
756 }
757
758 // If we got a new plan, then set it to be a controlling plan (User level
759 // Plans should be controlling plans so that they can be interruptible).
760 // Then resume the process.
761
762 if (new_plan_sp) {
763 new_plan_sp->SetIsControllingPlan(true);
764 new_plan_sp->SetOkayToDiscard(false);
765
766 if (m_options.m_step_count > 1) {
767 if (!new_plan_sp->SetIterationCount(m_options.m_step_count)) {
768 result.AppendWarning(
769 "step operation does not support iteration count");
770 }
771 }
772
773 process->GetThreadList().SetSelectedThreadByID(thread->GetID());
774
775 const uint32_t iohandler_id = process->GetIOHandlerID();
776
777 StreamString stream;
779 if (synchronous_execution)
780 error = process->ResumeSynchronous(&stream);
781 else
782 error = process->Resume();
783
784 if (!error.Success()) {
785 result.AppendMessage(error.AsCString());
787 return;
788 }
789
790 // There is a race condition where this thread will return up the call
791 // stack to the main command handler and show an (lldb) prompt before
792 // HandlePrivateEvent (from PrivateStateThread) has a chance to call
793 // PushProcessIOHandler().
794 process->SyncIOHandler(iohandler_id, std::chrono::seconds(2));
795
796 if (synchronous_execution) {
797 // If any state changed events had anything to say, add that to the
798 // result
799 if (stream.GetSize() > 0)
800 result.AppendMessage(stream.GetString());
801
802 process->GetThreadList().SetSelectedThreadByID(thread->GetID());
803 result.SetDidChangeProcessState(true);
805 } else {
807 }
808 } else {
809 result.SetError(std::move(new_plan_status));
810 }
811 }
812
817};
818
819// CommandObjectThreadContinue
820
822public:
825 interpreter, "thread continue",
826 "Continue execution of the current target process. One "
827 "or more threads may be specified, by default all "
828 "threads continue.",
829 nullptr,
830 eCommandRequiresThread | eCommandTryTargetAPILock |
831 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused) {
833 }
834
835 ~CommandObjectThreadContinue() override = default;
836
837 void DoExecute(Args &command, CommandReturnObject &result) override {
838 bool synchronous_execution = m_interpreter.GetSynchronous();
839
840 Process *process = m_exe_ctx.GetProcessPtr();
841 if (process == nullptr) {
842 result.AppendError("no process exists. Cannot continue");
843 return;
844 }
845
846 StateType state = process->GetState();
847 if ((state == eStateCrashed) || (state == eStateStopped) ||
848 (state == eStateSuspended)) {
849 const size_t argc = command.GetArgumentCount();
850 if (argc > 0) {
851 // These two lines appear at the beginning of both blocks in this
852 // if..else, but that is because we need to release the lock before
853 // calling process->Resume below.
854 std::lock_guard<std::recursive_mutex> guard(
855 process->GetThreadList().GetMutex());
856 const uint32_t num_threads = process->GetThreadList().GetSize();
857 std::vector<Thread *> resume_threads;
858 for (auto &entry : command.entries()) {
859 uint32_t thread_idx;
860 if (entry.ref().getAsInteger(0, thread_idx)) {
862 "invalid thread index argument: \"%s\"", entry.c_str());
863 return;
864 }
865 Thread *thread =
866 process->GetThreadList().FindThreadByIndexID(thread_idx).get();
867
868 if (thread) {
869 resume_threads.push_back(thread);
870 } else {
871 result.AppendErrorWithFormat("invalid thread index %u", thread_idx);
872 return;
873 }
874 }
875
876 if (resume_threads.empty()) {
877 result.AppendError("no valid thread indexes were specified");
878 return;
879 } else {
880 Stream &strm = result.GetOutputStream();
881 if (resume_threads.size() == 1)
882 strm << "Resuming thread: ";
883 else
884 strm << "Resuming threads: ";
885
886 for (uint32_t idx = 0; idx < num_threads; ++idx) {
887 Thread *thread =
888 process->GetThreadList().GetThreadAtIndex(idx).get();
889 std::vector<Thread *>::iterator this_thread_pos =
890 find(resume_threads.begin(), resume_threads.end(), thread);
891
892 if (this_thread_pos != resume_threads.end()) {
893 resume_threads.erase(this_thread_pos);
894 if (!resume_threads.empty())
895 strm << llvm::formatv("{0}, ", thread->GetIndexID());
896 else
897 strm << llvm::formatv("{0} ", thread->GetIndexID());
898
899 const bool override_suspend = true;
900 thread->SetResumeState(eStateRunning, override_suspend);
901 } else {
902 thread->SetResumeState(eStateSuspended);
903 }
904 }
905 result.AppendMessageWithFormatv("in process {0}", process->GetID());
906 }
907 } else {
908 // These two lines appear at the beginning of both blocks in this
909 // if..else, but that is because we need to release the lock before
910 // calling process->Resume below.
911 std::lock_guard<std::recursive_mutex> guard(
912 process->GetThreadList().GetMutex());
913 const uint32_t num_threads = process->GetThreadList().GetSize();
914 Thread *current_thread = GetDefaultThread();
915 if (current_thread == nullptr) {
916 result.AppendError("the process doesn't have a current thread");
917 return;
918 }
919 // Set the actions that the threads should each take when resuming
920 for (uint32_t idx = 0; idx < num_threads; ++idx) {
921 Thread *thread = process->GetThreadList().GetThreadAtIndex(idx).get();
922 if (thread == current_thread) {
924 "Resuming thread {0:x4} in process {1}", thread->GetID(),
925 process->GetID());
926 const bool override_suspend = true;
927 thread->SetResumeState(eStateRunning, override_suspend);
928 } else {
929 thread->SetResumeState(eStateSuspended);
930 }
931 }
932 }
933
934 StreamString stream;
936 if (synchronous_execution)
937 error = process->ResumeSynchronous(&stream);
938 else
939 error = process->Resume();
940
941 // We should not be holding the thread list lock when we do this.
942 if (error.Success()) {
943 result.AppendMessageWithFormatv("Process {0} resuming",
944 process->GetID());
945 if (synchronous_execution) {
946 // If any state changed events had anything to say, add that to the
947 // result
948 if (stream.GetSize() > 0)
949 result.AppendMessage(stream.GetString());
950
951 result.SetDidChangeProcessState(true);
953 } else {
955 }
956 } else {
957 result.AppendErrorWithFormat("Failed to resume process: %s",
958 error.AsCString());
959 }
960 } else {
962 "Process cannot be continued from its current state (%s)",
963 StateAsCString(state));
964 }
965 }
966};
967
968// CommandObjectThreadUntil
969
970#define LLDB_OPTIONS_thread_until
971#include "CommandOptions.inc"
972
974public:
975 class CommandOptions : public Options {
976 public:
979
981 // Keep default values of all options in one place: OptionParsingStarting
982 // ()
983 OptionParsingStarting(nullptr);
984 }
985
986 ~CommandOptions() override = default;
987
988 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
989 ExecutionContext *execution_context) override {
991 const int short_option = m_getopt_table[option_idx].val;
992
993 switch (short_option) {
994 case 'a': {
996 execution_context, option_arg, LLDB_INVALID_ADDRESS, &error);
997 if (error.Success())
998 m_until_addrs.push_back(tmp_addr);
999 } break;
1000 case 't':
1001 if (option_arg.getAsInteger(0, m_thread_idx)) {
1003 error = Status::FromErrorStringWithFormat("invalid thread index '%s'",
1004 option_arg.str().c_str());
1005 }
1006 break;
1007 case 'f':
1008 if (option_arg.getAsInteger(0, m_frame_idx)) {
1010 error = Status::FromErrorStringWithFormat("invalid frame index '%s'",
1011 option_arg.str().c_str());
1012 }
1013 break;
1014 case 'm': {
1015 auto enum_values = GetDefinitions()[option_idx].enum_values;
1017 option_arg, enum_values, eOnlyDuringStepping, error);
1018
1019 if (error.Success()) {
1020 if (run_mode == eAllThreads)
1021 m_stop_others = false;
1022 else
1023 m_stop_others = true;
1024 }
1025 } break;
1026 default:
1027 llvm_unreachable("Unimplemented option");
1028 }
1029 return error;
1030 }
1031
1032 void OptionParsingStarting(ExecutionContext *execution_context) override {
1034 m_frame_idx = 0;
1035 m_stop_others = false;
1036 m_until_addrs.clear();
1037 }
1038
1039 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
1040 return llvm::ArrayRef(g_thread_until_options);
1041 }
1042
1043 bool m_stop_others = false;
1044 std::vector<lldb::addr_t> m_until_addrs;
1045
1046 // Instance variables to hold the values for command options.
1047 };
1048
1051 interpreter, "thread until",
1052 "Continue until a line number or address is reached by the "
1053 "current or specified thread. Stops when returning from "
1054 "the current function as a safety measure. "
1055 "The target line number(s) are given as arguments, and if more "
1056 "than one"
1057 " is provided, stepping will stop when the first one is hit.",
1058 nullptr,
1059 eCommandRequiresThread | eCommandTryTargetAPILock |
1060 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused) {
1062 }
1063
1064 ~CommandObjectThreadUntil() override = default;
1065
1066 Options *GetOptions() override { return &m_options; }
1067
1068protected:
1069 void DoExecute(Args &command, CommandReturnObject &result) override {
1070 bool synchronous_execution = m_interpreter.GetSynchronous();
1071
1072 Target *target = GetTarget();
1073
1074 Process *process = m_exe_ctx.GetProcessPtr();
1075 if (process == nullptr) {
1076 result.AppendError("need a valid process to step");
1077 } else {
1078 Thread *thread = nullptr;
1079 std::vector<uint32_t> line_numbers;
1080
1081 if (command.GetArgumentCount() >= 1) {
1082 size_t num_args = command.GetArgumentCount();
1083 for (size_t i = 0; i < num_args; i++) {
1084 uint32_t line_number;
1085 if (!llvm::to_integer(command.GetArgumentAtIndex(i), line_number)) {
1086 result.AppendErrorWithFormat("invalid line number: '%s'",
1087 command.GetArgumentAtIndex(i));
1088 return;
1089 } else
1090 line_numbers.push_back(line_number);
1091 }
1092 } else if (m_options.m_until_addrs.empty()) {
1093 result.AppendErrorWithFormat("No line number or address provided:\n%s",
1094 GetSyntax().str().c_str());
1095 return;
1096 }
1097
1098 if (m_options.m_thread_idx == LLDB_INVALID_THREAD_ID) {
1099 thread = GetDefaultThread();
1100 } else {
1101 thread = process->GetThreadList()
1102 .FindThreadByIndexID(m_options.m_thread_idx)
1103 .get();
1104 }
1105
1106 if (thread == nullptr) {
1107 const uint32_t num_threads = process->GetThreadList().GetSize();
1108 result.AppendErrorWithFormat(
1109 "Thread index %u is out of range (valid values are 0 - %u)",
1110 m_options.m_thread_idx, num_threads);
1111 return;
1112 }
1113
1114 const bool abort_other_plans = false;
1115
1116 StackFrame *frame =
1117 thread->GetStackFrameAtIndex(m_options.m_frame_idx).get();
1118 if (frame == nullptr) {
1119 result.AppendErrorWithFormat(
1120 "Frame index %u is out of range for thread id %" PRIu64,
1121 m_options.m_frame_idx, thread->GetID());
1122 return;
1123 }
1124
1125 ThreadPlanSP new_plan_sp;
1126 Status new_plan_status;
1127
1128 if (frame->HasDebugInformation()) {
1129 // Finally we got here... Translate the given line number to a bunch
1130 // of addresses:
1131 SymbolContext sc(frame->GetSymbolContext(eSymbolContextCompUnit));
1132 LineTable *line_table = nullptr;
1133 if (sc.comp_unit)
1134 line_table = sc.comp_unit->GetLineTable();
1135
1136 if (line_table == nullptr) {
1137 result.AppendErrorWithFormat("Failed to resolve the line table for "
1138 "frame %u of thread id %" PRIu64,
1139 m_options.m_frame_idx, thread->GetID());
1140 return;
1141 }
1142
1143 LineEntry function_start;
1144 std::vector<addr_t> address_list;
1145
1146 // Find the beginning & end index of the function, but first make
1147 // sure it is valid:
1148 if (!sc.function) {
1149 result.AppendErrorWithFormat("Have debug information but no "
1150 "function info - can't get until range");
1151 return;
1152 }
1153
1154 RangeVector<uint32_t, uint32_t> line_idx_ranges;
1155 for (const AddressRange &range : sc.function->GetAddressRanges()) {
1156 auto [begin, end] = line_table->GetLineEntryIndexRange(range);
1157 line_idx_ranges.Append(begin, end - begin);
1158 }
1159 line_idx_ranges.Sort();
1160
1161 bool found_something = false;
1162
1163 // Since not all source lines will contribute code, check if we are
1164 // setting the breakpoint on the exact line number or the nearest
1165 // subsequent line number and set breakpoints at all the line table
1166 // entries of the chosen line number (exact or nearest subsequent).
1167 for (uint32_t line_number : line_numbers) {
1168 LineEntry line_entry;
1169 bool exact = false;
1170 if (sc.comp_unit->FindLineEntry(0, line_number, nullptr, exact,
1171 &line_entry) == UINT32_MAX)
1172 continue;
1173
1174 found_something = true;
1175 line_number = line_entry.line;
1176 exact = true;
1177 uint32_t end_func_idx = line_idx_ranges.GetMaxRangeEnd(0);
1178 uint32_t idx = sc.comp_unit->FindLineEntry(
1179 line_idx_ranges.GetMinRangeBase(UINT32_MAX), line_number, nullptr,
1180 exact, &line_entry);
1181 while (idx < end_func_idx) {
1182 if (line_idx_ranges.FindEntryIndexThatContains(idx) != UINT32_MAX) {
1183 addr_t address =
1184 line_entry.range.GetBaseAddress().GetLoadAddress(target);
1185 if (address != LLDB_INVALID_ADDRESS)
1186 address_list.push_back(address);
1187 }
1188 idx = sc.comp_unit->FindLineEntry(idx + 1, line_number, nullptr,
1189 exact, &line_entry);
1190 }
1191 }
1192
1193 for (lldb::addr_t address : m_options.m_until_addrs) {
1194 AddressRange unused;
1195 if (sc.function->GetRangeContainingLoadAddress(address, *target,
1196 unused))
1197 address_list.push_back(address);
1198 }
1199
1200 if (address_list.empty()) {
1201 if (found_something)
1202 result.AppendErrorWithFormat(
1203 "Until target outside of the current function");
1204 else
1205 result.AppendErrorWithFormat(
1206 "No line entries matching until target");
1207
1208 return;
1209 }
1210
1211 new_plan_sp = thread->QueueThreadPlanForStepUntil(
1212 abort_other_plans, address_list, m_options.m_stop_others,
1213 m_options.m_frame_idx, new_plan_status);
1214 if (new_plan_sp) {
1215 // User level plans should be controlling plans so they can be
1216 // interrupted
1217 // (e.g. by hitting a breakpoint) and other plans executed by the
1218 // user (stepping around the breakpoint) and then a "continue" will
1219 // resume the original plan.
1220 new_plan_sp->SetIsControllingPlan(true);
1221 new_plan_sp->SetOkayToDiscard(false);
1222 } else {
1223 result.SetError(std::move(new_plan_status));
1224 return;
1225 }
1226 } else {
1227 result.AppendErrorWithFormat("Frame index %u of thread id %" PRIu64
1228 " has no debug information",
1229 m_options.m_frame_idx, thread->GetID());
1230 return;
1231 }
1232
1233 if (!process->GetThreadList().SetSelectedThreadByID(thread->GetID())) {
1234 result.AppendErrorWithFormat(
1235 "Failed to set the selected thread to thread id %" PRIu64,
1236 thread->GetID());
1237 return;
1238 }
1239
1240 StreamString stream;
1241 Status error;
1242 if (synchronous_execution)
1243 error = process->ResumeSynchronous(&stream);
1244 else
1245 error = process->Resume();
1246
1247 if (error.Success()) {
1248 result.AppendMessageWithFormatv("Process {0} resuming",
1249 process->GetID());
1250 if (synchronous_execution) {
1251 // If any state changed events had anything to say, add that to the
1252 // result
1253 if (stream.GetSize() > 0)
1254 result.AppendMessage(stream.GetString());
1255
1256 result.SetDidChangeProcessState(true);
1258 } else {
1260 }
1261 } else {
1262 result.AppendErrorWithFormat("Failed to resume process: %s",
1263 error.AsCString());
1264 }
1265 }
1266 }
1267
1269};
1270
1271// CommandObjectThreadSelect
1272
1273#define LLDB_OPTIONS_thread_select
1274#include "CommandOptions.inc"
1275
1277public:
1279 public:
1281
1282 ~OptionGroupThreadSelect() override = default;
1283
1284 void OptionParsingStarting(ExecutionContext *execution_context) override {
1286 }
1287
1288 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1289 ExecutionContext *execution_context) override {
1290 const int short_option = g_thread_select_options[option_idx].short_option;
1291 switch (short_option) {
1292 case 't': {
1293 if (option_arg.getAsInteger(0, m_thread_id)) {
1295 return Status::FromErrorStringWithFormat("Invalid thread ID: '%s'.",
1296 option_arg.str().c_str());
1297 }
1298 break;
1299 }
1300
1301 default:
1302 llvm_unreachable("Unimplemented option");
1303 }
1304
1305 return {};
1306 }
1307
1308 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
1309 return llvm::ArrayRef(g_thread_select_options);
1310 }
1311
1313 };
1314
1316 : CommandObjectParsed(interpreter, "thread select",
1317 "Change the currently selected thread.",
1318 "thread select <thread-index> (or -t <thread-id>)",
1319 eCommandRequiresProcess | eCommandTryTargetAPILock |
1320 eCommandProcessMustBeLaunched |
1321 eCommandProcessMustBePaused) {
1323 CommandArgumentData thread_idx_arg;
1324
1325 // Define the first (and only) variant of this arg.
1326 thread_idx_arg.arg_type = eArgTypeThreadIndex;
1327 thread_idx_arg.arg_repetition = eArgRepeatPlain;
1328 thread_idx_arg.arg_opt_set_association = LLDB_OPT_SET_1;
1329
1330 // There is only one variant this argument could be; put it into the
1331 // argument entry.
1332 arg.push_back(thread_idx_arg);
1333
1334 // Push the data for the first argument into the m_arguments vector.
1335 m_arguments.push_back(arg);
1336
1338 m_option_group.Finalize();
1339 }
1340
1341 ~CommandObjectThreadSelect() override = default;
1342
1343 void
1345 OptionElementVector &opt_element_vector) override {
1346 if (request.GetCursorIndex())
1347 return;
1348
1351 nullptr);
1352 }
1353
1354 Options *GetOptions() override { return &m_option_group; }
1355
1356protected:
1357 void DoExecute(Args &command, CommandReturnObject &result) override {
1358 Process *process = m_exe_ctx.GetProcessPtr();
1359 if (process == nullptr) {
1360 result.AppendError("no process");
1361 return;
1362 } else if (m_options.m_thread_id == LLDB_INVALID_THREAD_ID &&
1363 command.GetArgumentCount() != 1) {
1364 result.AppendErrorWithFormat(
1365 "'%s' takes exactly one thread index argument, or a thread ID "
1366 "option:\nUsage: %s",
1367 m_cmd_name.c_str(), m_cmd_syntax.c_str());
1368 return;
1369 } else if (m_options.m_thread_id != LLDB_INVALID_THREAD_ID &&
1370 command.GetArgumentCount() != 0) {
1371 result.AppendErrorWithFormat("'%s' cannot take both a thread ID option "
1372 "and a thread index argument:\nUsage: %s",
1373 m_cmd_name.c_str(), m_cmd_syntax.c_str());
1374 return;
1375 }
1376
1377 Thread *new_thread = nullptr;
1378 if (command.GetArgumentCount() == 1) {
1379 uint32_t index_id;
1380 if (!llvm::to_integer(command.GetArgumentAtIndex(0), index_id)) {
1381 result.AppendErrorWithFormat("Invalid thread index '%s'",
1382 command.GetArgumentAtIndex(0));
1383 return;
1384 }
1385 new_thread = process->GetThreadList().FindThreadByIndexID(index_id).get();
1386 if (new_thread == nullptr) {
1387 result.AppendErrorWithFormat("Invalid thread index #%s",
1388 command.GetArgumentAtIndex(0));
1389 return;
1390 }
1391 } else {
1392 new_thread =
1393 process->GetThreadList().FindThreadByID(m_options.m_thread_id).get();
1394 if (new_thread == nullptr) {
1395 result.AppendErrorWithFormat("Invalid thread ID %" PRIu64,
1396 m_options.m_thread_id);
1397 return;
1398 }
1399 }
1400
1401 process->GetThreadList().SetSelectedThreadByID(new_thread->GetID(), true);
1403 }
1404
1407};
1408
1409// CommandObjectThreadList
1410
1412public:
1415 interpreter, "thread list",
1416 "Show a summary of each thread in the current target process. "
1417 "Use 'settings set thread-format' to customize the individual "
1418 "thread listings.",
1419 "thread list",
1420 eCommandRequiresProcess | eCommandTryTargetAPILock |
1421 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused) {}
1422
1423 ~CommandObjectThreadList() override = default;
1424
1425protected:
1426 void DoExecute(Args &command, CommandReturnObject &result) override {
1427 Stream &strm = result.GetOutputStream();
1429 Process *process = m_exe_ctx.GetProcessPtr();
1430 const bool only_threads_with_stop_reason = false;
1431 const uint32_t start_frame = 0;
1432 const uint32_t num_frames = 0;
1433 const uint32_t num_frames_with_source = 0;
1434 process->GetStatus(strm);
1435 process->GetThreadStatus(strm, only_threads_with_stop_reason, start_frame,
1436 num_frames, num_frames_with_source, false);
1437 }
1438};
1439
1440// CommandObjectThreadInfo
1441#define LLDB_OPTIONS_thread_info
1442#include "CommandOptions.inc"
1443
1445public:
1446 class CommandOptions : public Options {
1447 public:
1449
1450 ~CommandOptions() override = default;
1451
1452 void OptionParsingStarting(ExecutionContext *execution_context) override {
1453 m_json_thread = false;
1454 m_json_stopinfo = false;
1455 m_backing_thread = false;
1456 }
1457
1458 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1459 ExecutionContext *execution_context) override {
1460 const int short_option = m_getopt_table[option_idx].val;
1461 Status error;
1462
1463 switch (short_option) {
1464 case 'j':
1465 m_json_thread = true;
1466 break;
1467
1468 case 's':
1469 m_json_stopinfo = true;
1470 break;
1471
1472 case 'b':
1473 m_backing_thread = true;
1474 break;
1475
1476 default:
1477 llvm_unreachable("Unimplemented option");
1478 }
1479 return error;
1480 }
1481
1482 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
1483 return llvm::ArrayRef(g_thread_info_options);
1484 }
1485
1489 };
1490
1493 interpreter, "thread info",
1494 "Show an extended summary of one or "
1495 "more threads. Defaults to the "
1496 "current thread.",
1497 "thread info",
1498 eCommandRequiresProcess | eCommandTryTargetAPILock |
1499 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused) {
1500 m_add_return = false;
1501 }
1502
1503 ~CommandObjectThreadInfo() override = default;
1504
1505 void
1512
1513 Options *GetOptions() override { return &m_options; }
1514
1516 ThreadSP thread_sp =
1517 m_exe_ctx.GetProcessPtr()->GetThreadList().FindThreadByID(tid);
1518 if (!thread_sp) {
1519 result.AppendErrorWithFormat("thread no longer exists: 0x%" PRIx64, tid);
1520 return false;
1521 }
1522
1523 Thread *thread = thread_sp.get();
1524 if (m_options.m_backing_thread && thread->GetBackingThread())
1525 thread = thread->GetBackingThread().get();
1526
1527 Stream &strm = result.GetOutputStream();
1528 if (!thread->GetDescription(strm, eDescriptionLevelFull,
1529 m_options.m_json_thread,
1530 m_options.m_json_stopinfo)) {
1531 result.AppendErrorWithFormat("error displaying info for thread: \"%d\"",
1532 thread->GetIndexID());
1533 return false;
1534 }
1535 return true;
1536 }
1537
1539};
1540
1541// CommandObjectThreadException
1542
1544public:
1547 interpreter, "thread exception",
1548 "Display the current exception object for a thread. Defaults to "
1549 "the current thread.",
1550 "thread exception",
1551 eCommandRequiresProcess | eCommandTryTargetAPILock |
1552 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused) {}
1553
1554 ~CommandObjectThreadException() override = default;
1555
1556 void
1563
1565 ThreadSP thread_sp =
1566 m_exe_ctx.GetProcessPtr()->GetThreadList().FindThreadByID(tid);
1567 if (!thread_sp) {
1568 result.AppendErrorWithFormat("thread no longer exists: 0x%" PRIx64, tid);
1569 return false;
1570 }
1571
1572 Stream &strm = result.GetOutputStream();
1573 ValueObjectSP exception_object_sp = thread_sp->GetCurrentException();
1574 if (exception_object_sp) {
1575 if (llvm::Error error = exception_object_sp->Dump(strm)) {
1576 result.AppendError(toString(std::move(error)));
1577 return false;
1578 }
1579 }
1580
1581 ThreadSP exception_thread_sp = thread_sp->GetCurrentExceptionBacktrace();
1582 if (exception_thread_sp && exception_thread_sp->IsValid()) {
1583 const uint32_t num_frames_with_source = 0;
1584 const bool stop_format = false;
1585 exception_thread_sp->GetStatus(strm, 0, UINT32_MAX,
1586 num_frames_with_source, stop_format,
1587 /*filtered*/ false);
1588 }
1589
1590 return true;
1591 }
1592};
1593
1595public:
1598 interpreter, "thread siginfo",
1599 "Display the current siginfo object for a thread. Defaults to "
1600 "the current thread.",
1601 "thread siginfo",
1602 eCommandRequiresProcess | eCommandTryTargetAPILock |
1603 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused) {}
1604
1605 ~CommandObjectThreadSiginfo() override = default;
1606
1607 void
1614
1616 ThreadSP thread_sp =
1617 m_exe_ctx.GetProcessPtr()->GetThreadList().FindThreadByID(tid);
1618 if (!thread_sp) {
1619 result.AppendErrorWithFormat("thread no longer exists: 0x%" PRIx64, tid);
1620 return false;
1621 }
1622
1623 Stream &strm = result.GetOutputStream();
1624 if (!thread_sp->GetDescription(strm, eDescriptionLevelFull, false, false)) {
1625 result.AppendErrorWithFormat("error displaying info for thread: \"%d\"",
1626 thread_sp->GetIndexID());
1627 return false;
1628 }
1629 ValueObjectSP exception_object_sp = thread_sp->GetSiginfoValue();
1630 if (exception_object_sp) {
1631 if (llvm::Error error = exception_object_sp->Dump(strm)) {
1632 result.AppendError(toString(std::move(error)));
1633 return false;
1634 }
1635 } else
1636 strm.Printf("(no siginfo)\n");
1637 strm.PutChar('\n');
1638
1639 return true;
1640 }
1641};
1642
1643// CommandObjectThreadReturn
1644#define LLDB_OPTIONS_thread_return
1645#include "CommandOptions.inc"
1646
1648public:
1649 class CommandOptions : public Options {
1650 public:
1652 // Keep default values of all options in one place: OptionParsingStarting
1653 // ()
1654 OptionParsingStarting(nullptr);
1655 }
1656
1657 ~CommandOptions() override = default;
1658
1659 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1660 ExecutionContext *execution_context) override {
1661 Status error;
1662 const int short_option = m_getopt_table[option_idx].val;
1663
1664 switch (short_option) {
1665 case 'x': {
1666 bool success;
1667 bool tmp_value =
1668 OptionArgParser::ToBoolean(option_arg, false, &success);
1669 if (success)
1670 m_from_expression = tmp_value;
1671 else {
1673 "invalid boolean value '%s' for 'x' option",
1674 option_arg.str().c_str());
1675 }
1676 } break;
1677 default:
1678 llvm_unreachable("Unimplemented option");
1679 }
1680 return error;
1681 }
1682
1683 void OptionParsingStarting(ExecutionContext *execution_context) override {
1684 m_from_expression = false;
1685 }
1686
1687 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
1688 return llvm::ArrayRef(g_thread_return_options);
1689 }
1690
1691 bool m_from_expression = false;
1692
1693 // Instance variables to hold the values for command options.
1694 };
1695
1697 : CommandObjectRaw(interpreter, "thread return",
1698 "Prematurely return from a stack frame, "
1699 "short-circuiting execution of newer frames "
1700 "and optionally yielding a specified value. Defaults "
1701 "to the exiting the current stack "
1702 "frame.",
1703 "thread return",
1704 eCommandRequiresFrame | eCommandTryTargetAPILock |
1705 eCommandProcessMustBeLaunched |
1706 eCommandProcessMustBePaused) {
1708 }
1709
1710 ~CommandObjectThreadReturn() override = default;
1711
1712 Options *GetOptions() override { return &m_options; }
1713
1714protected:
1715 void DoExecute(llvm::StringRef command,
1716 CommandReturnObject &result) override {
1717 // I am going to handle this by hand, because I don't want you to have to
1718 // say:
1719 // "thread return -- -5".
1720 if (command.starts_with("-x")) {
1721 if (command.size() != 2U)
1722 result.AppendWarning("return values ignored when returning from user "
1723 "called expressions");
1724
1725 Thread *thread = m_exe_ctx.GetThreadPtr();
1726 Status error;
1727 error = thread->UnwindInnermostExpression();
1728 if (!error.Success()) {
1729 result.AppendErrorWithFormat("Unwinding expression failed - %s",
1730 error.AsCString());
1731 } else {
1732 bool success =
1733 thread->SetSelectedFrameByIndexNoisily(0, result.GetOutputStream());
1734 if (success) {
1735 m_exe_ctx.SetFrameSP(
1736 thread->GetSelectedFrame(DoNoSelectMostRelevantFrame));
1738 } else {
1739 result.AppendErrorWithFormat(
1740 "Could not select 0th frame after unwinding expression");
1741 }
1742 }
1743 return;
1744 }
1745
1746 ValueObjectSP return_valobj_sp;
1747
1748 StackFrameSP frame_sp = m_exe_ctx.GetFrameSP();
1749 uint32_t frame_idx = frame_sp->GetFrameIndex();
1750
1751 if (frame_sp->IsInlined()) {
1752 result.AppendError("don't know how to return from inlined frames");
1753 return;
1754 }
1755
1756 if (!command.empty()) {
1757 Target *target = m_exe_ctx.GetTargetPtr();
1759
1760 options.SetUnwindOnError(true);
1762
1764 exe_results = target->EvaluateExpression(command, frame_sp.get(),
1765 return_valobj_sp, options);
1766 if (exe_results != eExpressionCompleted) {
1767 if (return_valobj_sp)
1768 result.AppendErrorWithFormat(
1769 "Error evaluating result expression: %s",
1770 return_valobj_sp->GetError().AsCString());
1771 else
1772 result.AppendErrorWithFormat(
1773 "Unknown error evaluating result expression");
1774 return;
1775 }
1776 }
1777
1778 Status error;
1779 ThreadSP thread_sp = m_exe_ctx.GetThreadSP();
1780 const bool broadcast = true;
1781 error = thread_sp->ReturnFromFrame(frame_sp, return_valobj_sp, broadcast);
1782 if (!error.Success()) {
1783 result.AppendErrorWithFormat(
1784 "Error returning from frame %d of thread %d: %s", frame_idx,
1785 thread_sp->GetIndexID(), error.AsCString());
1786 return;
1787 }
1788
1790 }
1791
1793};
1794
1795// CommandObjectThreadJump
1796#define LLDB_OPTIONS_thread_jump
1797#include "CommandOptions.inc"
1798
1800public:
1801 class CommandOptions : public Options {
1802 public:
1804
1805 ~CommandOptions() override = default;
1806
1807 void OptionParsingStarting(ExecutionContext *execution_context) override {
1808 m_filenames.Clear();
1809 m_line_num = 0;
1810 m_line_offset = 0;
1812 m_force = false;
1813 }
1814
1815 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1816 ExecutionContext *execution_context) override {
1817 const int short_option = m_getopt_table[option_idx].val;
1818 Status error;
1819
1820 switch (short_option) {
1821 case 'f':
1822 m_filenames.AppendIfUnique(FileSpec(option_arg));
1823 if (m_filenames.GetSize() > 1)
1824 return Status::FromErrorString("only one source file expected.");
1825 break;
1826 case 'l':
1827 if (option_arg.getAsInteger(0, m_line_num))
1828 return Status::FromErrorStringWithFormat("invalid line number: '%s'.",
1829 option_arg.str().c_str());
1830 break;
1831 case 'b': {
1832 option_arg.consume_front("+");
1833
1834 if (option_arg.getAsInteger(0, m_line_offset))
1835 return Status::FromErrorStringWithFormat("invalid line offset: '%s'.",
1836 option_arg.str().c_str());
1837 break;
1838 }
1839 case 'a':
1840 m_load_addr = OptionArgParser::ToAddress(execution_context, option_arg,
1842 break;
1843 case 'r':
1844 m_force = true;
1845 break;
1846 default:
1847 llvm_unreachable("Unimplemented option");
1848 }
1849 return error;
1850 }
1851
1852 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
1853 return llvm::ArrayRef(g_thread_jump_options);
1854 }
1855
1857 uint32_t m_line_num;
1861 };
1862
1865 interpreter, "thread jump",
1866 "Sets the program counter to a new address.", "thread jump",
1867 eCommandRequiresFrame | eCommandTryTargetAPILock |
1868 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused) {}
1869
1870 ~CommandObjectThreadJump() override = default;
1871
1872 Options *GetOptions() override { return &m_options; }
1873
1874protected:
1875 void DoExecute(Args &args, CommandReturnObject &result) override {
1876 RegisterContext *reg_ctx = m_exe_ctx.GetRegisterContext();
1877 StackFrame *frame = m_exe_ctx.GetFramePtr();
1878 Thread *thread = m_exe_ctx.GetThreadPtr();
1879 Target *target = m_exe_ctx.GetTargetPtr();
1880 const SymbolContext &sym_ctx =
1881 frame->GetSymbolContext(eSymbolContextLineEntry);
1882
1883 if (m_options.m_load_addr != LLDB_INVALID_ADDRESS) {
1884 // Use this address directly.
1885 Address dest = Address(m_options.m_load_addr);
1886
1887 lldb::addr_t callAddr = dest.GetCallableLoadAddress(target);
1888 if (callAddr == LLDB_INVALID_ADDRESS) {
1889 result.AppendErrorWithFormat("Invalid destination address");
1890 return;
1891 }
1892
1893 if (!reg_ctx->SetPC(callAddr)) {
1894 result.AppendErrorWithFormat("Error changing PC value for thread %d",
1895 thread->GetIndexID());
1896 return;
1897 }
1898 } else {
1899 // Pick either the absolute line, or work out a relative one.
1900 int32_t line = (int32_t)m_options.m_line_num;
1901 if (line == 0)
1902 line = sym_ctx.line_entry.line + m_options.m_line_offset;
1903
1904 // Try the current file, but override if asked.
1905 FileSpec file = sym_ctx.line_entry.GetFile();
1906 if (m_options.m_filenames.GetSize() == 1)
1907 file = m_options.m_filenames.GetFileSpecAtIndex(0);
1908
1909 if (!file) {
1910 result.AppendErrorWithFormat(
1911 "no source file available for the current location");
1912 return;
1913 }
1914
1915 std::string warnings;
1916 Status err = thread->JumpToLine(file, line, m_options.m_force, &warnings);
1917
1918 if (err.Fail()) {
1919 result.SetError(std::move(err));
1920 return;
1921 }
1922
1923 if (!warnings.empty())
1924 result.AppendWarning(warnings.c_str());
1925 }
1926
1928 }
1929
1931};
1932
1933// Next are the subcommands of CommandObjectMultiwordThreadPlan
1934
1935// CommandObjectThreadPlanList
1936#define LLDB_OPTIONS_thread_plan_list
1937#include "CommandOptions.inc"
1938
1940public:
1941 class CommandOptions : public Options {
1942 public:
1944 // Keep default values of all options in one place: OptionParsingStarting
1945 // ()
1946 OptionParsingStarting(nullptr);
1947 }
1948
1949 ~CommandOptions() override = default;
1950
1951 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1952 ExecutionContext *execution_context) override {
1953 const int short_option = m_getopt_table[option_idx].val;
1954
1955 switch (short_option) {
1956 case 'i':
1957 m_internal = true;
1958 break;
1959 case 't':
1960 lldb::tid_t tid;
1961 if (option_arg.getAsInteger(0, tid))
1962 return Status::FromErrorStringWithFormat("invalid tid: '%s'.",
1963 option_arg.str().c_str());
1964 m_tids.push_back(tid);
1965 break;
1966 case 'u':
1967 m_unreported = false;
1968 break;
1969 case 'v':
1970 m_verbose = true;
1971 break;
1972 default:
1973 llvm_unreachable("Unimplemented option");
1974 }
1975 return {};
1976 }
1977
1978 void OptionParsingStarting(ExecutionContext *execution_context) override {
1979 m_verbose = false;
1980 m_internal = false;
1981 m_unreported = true; // The variable is "skip unreported" and we want to
1982 // skip unreported by default.
1983 m_tids.clear();
1984 }
1985
1986 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
1987 return llvm::ArrayRef(g_thread_plan_list_options);
1988 }
1989
1990 // Instance variables to hold the values for command options.
1994 std::vector<lldb::tid_t> m_tids;
1995 };
1996
1999 interpreter, "thread plan list",
2000 "Show thread plans for one or more threads. If no threads are "
2001 "specified, show the "
2002 "current thread. Use the thread-index \"all\" to see all threads.",
2003 nullptr,
2004 eCommandRequiresProcess | eCommandRequiresThread |
2005 eCommandTryTargetAPILock | eCommandProcessMustBeLaunched |
2006 eCommandProcessMustBePaused) {}
2007
2008 ~CommandObjectThreadPlanList() override = default;
2009
2010 Options *GetOptions() override { return &m_options; }
2011
2012 void DoExecute(Args &command, CommandReturnObject &result) override {
2013 // If we are reporting all threads, dispatch to the Process to do that:
2014 if (command.GetArgumentCount() == 0 && m_options.m_tids.empty()) {
2015 Stream &strm = result.GetOutputStream();
2016 DescriptionLevel desc_level = m_options.m_verbose
2019 m_exe_ctx.GetProcessPtr()->DumpThreadPlans(
2020 strm, desc_level, m_options.m_internal, true, m_options.m_unreported);
2022 return;
2023 } else {
2024 // Do any TID's that the user may have specified as TID, then do any
2025 // Thread Indexes...
2026 if (!m_options.m_tids.empty()) {
2027 Process *process = m_exe_ctx.GetProcessPtr();
2028 StreamString tmp_strm;
2029 for (lldb::tid_t tid : m_options.m_tids) {
2030 bool success = process->DumpThreadPlansForTID(
2031 tmp_strm, tid, eDescriptionLevelFull, m_options.m_internal,
2032 true /* condense_trivial */, m_options.m_unreported);
2033 // If we didn't find a TID, stop here and return an error.
2034 if (!success) {
2035 result.AppendError("Error dumping plans:");
2036 result.AppendError(tmp_strm.GetString());
2037 return;
2038 }
2039 // Otherwise, add our data to the output:
2040 result.GetOutputStream() << tmp_strm.GetString();
2041 }
2042 }
2043 return CommandObjectIterateOverThreads::DoExecute(command, result);
2044 }
2045 }
2046
2047protected:
2049 // If we have already handled this from a -t option, skip it here.
2050 if (llvm::is_contained(m_options.m_tids, tid))
2051 return true;
2052
2053 Process *process = m_exe_ctx.GetProcessPtr();
2054
2055 Stream &strm = result.GetOutputStream();
2057 if (m_options.m_verbose)
2058 desc_level = eDescriptionLevelVerbose;
2059
2060 process->DumpThreadPlansForTID(strm, tid, desc_level, m_options.m_internal,
2061 true /* condense_trivial */,
2062 m_options.m_unreported);
2063 return true;
2064 }
2065
2067};
2068
2070public:
2072 : CommandObjectParsed(interpreter, "thread plan discard",
2073 "Discards thread plans up to and including the "
2074 "specified index (see 'thread plan list'.) "
2075 "Only user visible plans can be discarded.",
2076 nullptr,
2077 eCommandRequiresProcess | eCommandRequiresThread |
2078 eCommandTryTargetAPILock |
2079 eCommandProcessMustBeLaunched |
2080 eCommandProcessMustBePaused) {
2082 }
2083
2085
2086 void
2088 OptionElementVector &opt_element_vector) override {
2089 if (!m_exe_ctx.HasThreadScope() || request.GetCursorIndex())
2090 return;
2091
2092 m_exe_ctx.GetThreadPtr()->AutoCompleteThreadPlans(request);
2093 }
2094
2095 void DoExecute(Args &args, CommandReturnObject &result) override {
2096 Thread *thread = m_exe_ctx.GetThreadPtr();
2097 if (args.GetArgumentCount() != 1) {
2098 result.AppendErrorWithFormat("Too many arguments, expected one - the "
2099 "thread plan index - but got %zu",
2100 args.GetArgumentCount());
2101 return;
2102 }
2103
2104 uint32_t thread_plan_idx;
2105 if (!llvm::to_integer(args.GetArgumentAtIndex(0), thread_plan_idx)) {
2106 result.AppendErrorWithFormat(
2107 "Invalid thread index: \"%s\" - should be unsigned int",
2108 args.GetArgumentAtIndex(0));
2109 return;
2110 }
2111
2112 if (thread_plan_idx == 0) {
2113 result.AppendErrorWithFormat(
2114 "You wouldn't really want me to discard the base thread plan");
2115 return;
2116 }
2117
2118 if (thread->DiscardUserThreadPlansUpToIndex(thread_plan_idx)) {
2120 } else {
2121 result.AppendErrorWithFormat(
2122 "Could not find User thread plan with index %s",
2123 args.GetArgumentAtIndex(0));
2124 }
2125 }
2126};
2127
2129public:
2131 : CommandObjectParsed(interpreter, "thread plan prune",
2132 "Removes any thread plans associated with "
2133 "currently unreported threads. "
2134 "Specify one or more TID's to remove, or if no "
2135 "TID's are provides, remove threads for all "
2136 "unreported threads",
2137 nullptr,
2138 eCommandRequiresProcess |
2139 eCommandTryTargetAPILock |
2140 eCommandProcessMustBeLaunched |
2141 eCommandProcessMustBePaused) {
2143 }
2144
2145 ~CommandObjectThreadPlanPrune() override = default;
2146
2147 void DoExecute(Args &args, CommandReturnObject &result) override {
2148 Process *process = m_exe_ctx.GetProcessPtr();
2149
2150 if (args.GetArgumentCount() == 0) {
2151 process->PruneThreadPlans();
2153 return;
2154 }
2155
2156 const size_t num_args = args.GetArgumentCount();
2157
2158 std::lock_guard<std::recursive_mutex> guard(
2159 process->GetThreadList().GetMutex());
2160
2161 for (size_t i = 0; i < num_args; i++) {
2162 lldb::tid_t tid;
2163 if (!llvm::to_integer(args.GetArgumentAtIndex(i), tid)) {
2164 result.AppendErrorWithFormat("invalid thread specification: \"%s\"",
2165 args.GetArgumentAtIndex(i));
2166 return;
2167 }
2168 if (!process->PruneThreadPlansForTID(tid)) {
2169 result.AppendErrorWithFormat("Could not find unreported tid: \"%s\"",
2170 args.GetArgumentAtIndex(i));
2171 return;
2172 }
2173 }
2175 }
2176};
2177
2178// CommandObjectMultiwordThreadPlan
2179
2181public:
2184 interpreter, "plan",
2185 "Commands for managing thread plans that control execution.",
2186 "thread plan <subcommand> [<subcommand objects]") {
2188 "list", CommandObjectSP(new CommandObjectThreadPlanList(interpreter)));
2190 "discard",
2193 "prune",
2195 }
2196
2198};
2199
2200// Next are the subcommands of CommandObjectMultiwordTrace
2201
2202// CommandObjectTraceExport
2203
2205public:
2208 interpreter, "trace thread export",
2209 "Commands for exporting traces of the threads in the current "
2210 "process to different formats.",
2211 "thread trace export <export-plugin> [<subcommand objects>]") {
2212
2213 for (auto &cbs : PluginManager::GetTraceExporterCallbacks()) {
2214 if (cbs.create_thread_trace_export_command)
2215 LoadSubCommand(cbs.name,
2216 cbs.create_thread_trace_export_command(interpreter));
2217 }
2218 }
2219};
2220
2221// CommandObjectTraceStart
2222
2224public:
2227 /*live_debug_session_only=*/true, interpreter, "thread trace start",
2228 "Start tracing threads with the corresponding trace "
2229 "plug-in for the current process.",
2230 "thread trace start [<trace-options>]") {}
2231
2232protected:
2236};
2237
2238// CommandObjectTraceStop
2239
2241public:
2244 interpreter, "thread trace stop",
2245 "Stop tracing threads, including the ones traced with the "
2246 "\"process trace start\" command."
2247 "Defaults to the current thread. Thread indices can be "
2248 "specified as arguments.\n Use the thread-index \"all\" to stop "
2249 "tracing "
2250 "for all existing threads.",
2251 "thread trace stop [<thread-index> <thread-index> ...]",
2252 eCommandRequiresProcess | eCommandTryTargetAPILock |
2253 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused |
2254 eCommandProcessMustBeTraced) {}
2255
2256 ~CommandObjectTraceStop() override = default;
2257
2259 llvm::ArrayRef<lldb::tid_t> tids) override {
2260 ProcessSP process_sp = m_exe_ctx.GetProcessSP();
2261
2262 TraceSP trace_sp = process_sp->GetTarget().GetTrace();
2263
2264 if (llvm::Error err = trace_sp->Stop(tids))
2265 result.AppendError(toString(std::move(err)));
2266 else
2268
2269 return result.Succeeded();
2270 }
2271};
2272
2274 CommandReturnObject &result) {
2275 if (args.GetArgumentCount() == 0)
2276 return exe_ctx.GetThreadSP();
2277
2278 const char *arg = args.GetArgumentAtIndex(0);
2279 uint32_t thread_idx;
2280
2281 if (!llvm::to_integer(arg, thread_idx)) {
2282 result.AppendErrorWithFormat("invalid thread specification: \"%s\"", arg);
2283 return nullptr;
2284 }
2285 ThreadSP thread_sp =
2286 exe_ctx.GetProcessRef().GetThreadList().FindThreadByIndexID(thread_idx);
2287 if (!thread_sp)
2288 result.AppendErrorWithFormat("no thread with index: \"%s\"", arg);
2289 return thread_sp;
2290}
2291
2292// CommandObjectTraceDumpFunctionCalls
2293#define LLDB_OPTIONS_thread_trace_dump_function_calls
2294#include "CommandOptions.inc"
2295
2297public:
2298 class CommandOptions : public Options {
2299 public:
2301
2302 ~CommandOptions() override = default;
2303
2304 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
2305 ExecutionContext *execution_context) override {
2306 Status error;
2307 const int short_option = m_getopt_table[option_idx].val;
2308
2309 switch (short_option) {
2310 case 'j': {
2311 m_dumper_options.json = true;
2312 break;
2313 }
2314 case 'J': {
2315 m_dumper_options.json = true;
2316 m_dumper_options.pretty_print_json = true;
2317 break;
2318 }
2319 case 'F': {
2320 m_output_file.emplace(option_arg);
2321 break;
2322 }
2323 default:
2324 llvm_unreachable("Unimplemented option");
2325 }
2326 return error;
2327 }
2328
2329 void OptionParsingStarting(ExecutionContext *execution_context) override {
2330 m_dumper_options = {};
2331 m_output_file = std::nullopt;
2332 }
2333
2334 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
2335 return llvm::ArrayRef(g_thread_trace_dump_function_calls_options);
2336 }
2337
2338 static const size_t kDefaultCount = 20;
2339
2340 // Instance variables to hold the values for command options.
2342 std::optional<FileSpec> m_output_file;
2343 };
2344
2347 interpreter, "thread trace dump function-calls",
2348 "Dump the traced function-calls for one thread. If no "
2349 "thread is specified, the current thread is used.",
2350 nullptr,
2351 eCommandRequiresProcess | eCommandRequiresThread |
2352 eCommandTryTargetAPILock | eCommandProcessMustBeLaunched |
2353 eCommandProcessMustBePaused | eCommandProcessMustBeTraced) {
2355 }
2356
2358
2359 Options *GetOptions() override { return &m_options; }
2360
2361protected:
2362 void DoExecute(Args &args, CommandReturnObject &result) override {
2363 ThreadSP thread_sp = GetSingleThreadFromArgs(m_exe_ctx, args, result);
2364 if (!thread_sp) {
2365 result.AppendError("invalid thread\n");
2366 return;
2367 }
2368
2369 llvm::Expected<TraceCursorSP> cursor_or_error =
2370 m_exe_ctx.GetTargetSP()->GetTrace()->CreateNewCursor(*thread_sp);
2371
2372 if (!cursor_or_error) {
2373 result.AppendError(llvm::toString(cursor_or_error.takeError()));
2374 return;
2375 }
2376 TraceCursorSP &cursor_sp = *cursor_or_error;
2377
2378 std::optional<StreamFile> out_file;
2379 if (m_options.m_output_file) {
2380 out_file.emplace(m_options.m_output_file->GetPath().c_str(),
2383 }
2384
2385 m_options.m_dumper_options.forwards = true;
2386
2387 TraceDumper dumper(std::move(cursor_sp),
2388 out_file ? *out_file : result.GetOutputStream(),
2389 m_options.m_dumper_options);
2390
2391 dumper.DumpFunctionCalls();
2392 }
2393
2395};
2396
2397// CommandObjectTraceDumpInstructions
2398#define LLDB_OPTIONS_thread_trace_dump_instructions
2399#include "CommandOptions.inc"
2400
2402public:
2403 class CommandOptions : public Options {
2404 public:
2406
2407 ~CommandOptions() override = default;
2408
2409 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
2410 ExecutionContext *execution_context) override {
2411 Status error;
2412 const int short_option = m_getopt_table[option_idx].val;
2413
2414 switch (short_option) {
2415 case 'c': {
2416 int32_t count;
2417 if (option_arg.empty() || option_arg.getAsInteger(0, count) ||
2418 count < 0)
2420 "invalid integer value for option '%s'",
2421 option_arg.str().c_str());
2422 else
2423 m_count = count;
2424 break;
2425 }
2426 case 'a': {
2427 m_count = std::numeric_limits<decltype(m_count)>::max();
2428 break;
2429 }
2430 case 's': {
2431 int32_t skip;
2432 if (option_arg.empty() || option_arg.getAsInteger(0, skip) || skip < 0)
2434 "invalid integer value for option '%s'",
2435 option_arg.str().c_str());
2436 else
2437 m_dumper_options.skip = skip;
2438 break;
2439 }
2440 case 'i': {
2441 uint64_t id;
2442 if (option_arg.empty() || option_arg.getAsInteger(0, id))
2444 "invalid integer value for option '%s'",
2445 option_arg.str().c_str());
2446 else
2447 m_dumper_options.id = id;
2448 break;
2449 }
2450 case 'F': {
2451 m_output_file.emplace(option_arg);
2452 break;
2453 }
2454 case 'r': {
2455 m_dumper_options.raw = true;
2456 break;
2457 }
2458 case 'f': {
2459 m_dumper_options.forwards = true;
2460 break;
2461 }
2462 case 'k': {
2463 m_dumper_options.show_control_flow_kind = true;
2464 break;
2465 }
2466 case 't': {
2467 m_dumper_options.show_timestamps = true;
2468 break;
2469 }
2470 case 'e': {
2471 m_dumper_options.show_events = true;
2472 break;
2473 }
2474 case 'j': {
2475 m_dumper_options.json = true;
2476 break;
2477 }
2478 case 'J': {
2479 m_dumper_options.pretty_print_json = true;
2480 m_dumper_options.json = true;
2481 break;
2482 }
2483 case 'E': {
2484 m_dumper_options.only_events = true;
2485 m_dumper_options.show_events = true;
2486 break;
2487 }
2488 case 'C': {
2489 m_continue = true;
2490 break;
2491 }
2492 default:
2493 llvm_unreachable("Unimplemented option");
2494 }
2495 return error;
2496 }
2497
2498 void OptionParsingStarting(ExecutionContext *execution_context) override {
2500 m_continue = false;
2501 m_output_file = std::nullopt;
2502 m_dumper_options = {};
2503 }
2504
2505 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
2506 return llvm::ArrayRef(g_thread_trace_dump_instructions_options);
2507 }
2508
2509 static const size_t kDefaultCount = 20;
2510
2511 // Instance variables to hold the values for command options.
2512 size_t m_count;
2514 std::optional<FileSpec> m_output_file;
2516 };
2517
2520 interpreter, "thread trace dump instructions",
2521 "Dump the traced instructions for one thread. If no "
2522 "thread is specified, show the current thread.",
2523 nullptr,
2524 eCommandRequiresProcess | eCommandRequiresThread |
2525 eCommandTryTargetAPILock | eCommandProcessMustBeLaunched |
2526 eCommandProcessMustBePaused | eCommandProcessMustBeTraced) {
2528 }
2529
2531
2532 Options *GetOptions() override { return &m_options; }
2533
2534 std::optional<std::string> GetRepeatCommand(Args &current_command_args,
2535 uint32_t index) override {
2536 std::string cmd;
2537 current_command_args.GetCommandString(cmd);
2538 if (cmd.find(" --continue") == std::string::npos)
2539 cmd += " --continue";
2540 return cmd;
2541 }
2542
2543protected:
2544 void DoExecute(Args &args, CommandReturnObject &result) override {
2545 ThreadSP thread_sp = GetSingleThreadFromArgs(m_exe_ctx, args, result);
2546 if (!thread_sp) {
2547 result.AppendError("invalid thread\n");
2548 return;
2549 }
2550
2551 if (m_options.m_continue && m_last_id) {
2552 // We set up the options to continue one instruction past where
2553 // the previous iteration stopped.
2554 m_options.m_dumper_options.skip = 1;
2555 m_options.m_dumper_options.id = m_last_id;
2556 }
2557
2558 llvm::Expected<TraceCursorSP> cursor_or_error =
2559 m_exe_ctx.GetTargetSP()->GetTrace()->CreateNewCursor(*thread_sp);
2560
2561 if (!cursor_or_error) {
2562 result.AppendError(llvm::toString(cursor_or_error.takeError()));
2563 return;
2564 }
2565 TraceCursorSP &cursor_sp = *cursor_or_error;
2566
2567 if (m_options.m_dumper_options.id &&
2568 !cursor_sp->HasId(*m_options.m_dumper_options.id)) {
2569 result.AppendError("invalid instruction id\n");
2570 return;
2571 }
2572
2573 std::optional<StreamFile> out_file;
2574 if (m_options.m_output_file) {
2575 out_file.emplace(m_options.m_output_file->GetPath().c_str(),
2578 }
2579
2580 if (m_options.m_continue && !m_last_id) {
2581 // We need to stop processing data when we already ran out of instructions
2582 // in a previous command. We can fake this by setting the cursor past the
2583 // end of the trace.
2584 cursor_sp->Seek(1, lldb::eTraceCursorSeekTypeEnd);
2585 }
2586
2587 TraceDumper dumper(std::move(cursor_sp),
2588 out_file ? *out_file : result.GetOutputStream(),
2589 m_options.m_dumper_options);
2590
2591 m_last_id = dumper.DumpInstructions(m_options.m_count);
2592 }
2593
2595 // Last traversed id used to continue a repeat command. std::nullopt means
2596 // that all the trace has been consumed.
2597 std::optional<lldb::user_id_t> m_last_id;
2598};
2599
2600// CommandObjectTraceDumpInfo
2601#define LLDB_OPTIONS_thread_trace_dump_info
2602#include "CommandOptions.inc"
2603
2605public:
2606 class CommandOptions : public Options {
2607 public:
2609
2610 ~CommandOptions() override = default;
2611
2612 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
2613 ExecutionContext *execution_context) override {
2614 Status error;
2615 const int short_option = m_getopt_table[option_idx].val;
2616
2617 switch (short_option) {
2618 case 'v': {
2619 m_verbose = true;
2620 break;
2621 }
2622 case 'j': {
2623 m_json = true;
2624 break;
2625 }
2626 default:
2627 llvm_unreachable("Unimplemented option");
2628 }
2629 return error;
2630 }
2631
2632 void OptionParsingStarting(ExecutionContext *execution_context) override {
2633 m_verbose = false;
2634 m_json = false;
2635 }
2636
2637 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
2638 return llvm::ArrayRef(g_thread_trace_dump_info_options);
2639 }
2640
2641 // Instance variables to hold the values for command options.
2644 };
2645
2648 interpreter, "thread trace dump info",
2649 "Dump the traced information for one or more threads. If no "
2650 "threads are specified, show the current thread. Use the "
2651 "thread-index \"all\" to see all threads.",
2652 nullptr,
2653 eCommandRequiresProcess | eCommandTryTargetAPILock |
2654 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused |
2655 eCommandProcessMustBeTraced) {}
2656
2657 ~CommandObjectTraceDumpInfo() override = default;
2658
2659 Options *GetOptions() override { return &m_options; }
2660
2661protected:
2663 const TraceSP &trace_sp = m_exe_ctx.GetTargetSP()->GetTrace();
2664 ThreadSP thread_sp =
2665 m_exe_ctx.GetProcessPtr()->GetThreadList().FindThreadByID(tid);
2666 trace_sp->DumpTraceInfo(*thread_sp, result.GetOutputStream(),
2667 m_options.m_verbose, m_options.m_json);
2668 return true;
2669 }
2670
2672};
2673
2674// CommandObjectMultiwordTraceDump
2676public:
2679 interpreter, "dump",
2680 "Commands for displaying trace information of the threads "
2681 "in the current process.",
2682 "thread trace dump <subcommand> [<subcommand objects>]") {
2684 "instructions",
2687 "function-calls",
2690 "info", CommandObjectSP(new CommandObjectTraceDumpInfo(interpreter)));
2691 }
2693};
2694
2695// CommandObjectMultiwordTrace
2697public:
2700 interpreter, "trace",
2701 "Commands for operating on traces of the threads in the current "
2702 "process.",
2703 "thread trace <subcommand> [<subcommand objects>]") {
2705 interpreter)));
2706 LoadSubCommand("start",
2707 CommandObjectSP(new CommandObjectTraceStart(interpreter)));
2708 LoadSubCommand("stop",
2709 CommandObjectSP(new CommandObjectTraceStop(interpreter)));
2710 LoadSubCommand("export",
2711 CommandObjectSP(new CommandObjectTraceExport(interpreter)));
2712 }
2713
2714 ~CommandObjectMultiwordTrace() override = default;
2715};
2716
2717// CommandObjectMultiwordThread
2718
2720 CommandInterpreter &interpreter)
2721 : CommandObjectMultiword(interpreter, "thread",
2722 "Commands for operating on "
2723 "one or more threads in "
2724 "the current process.",
2725 "thread <subcommand> [<subcommand-options>]") {
2727 interpreter)));
2728 LoadSubCommand("continue",
2730 LoadSubCommand("list",
2731 CommandObjectSP(new CommandObjectThreadList(interpreter)));
2732 LoadSubCommand("return",
2733 CommandObjectSP(new CommandObjectThreadReturn(interpreter)));
2734 LoadSubCommand("jump",
2735 CommandObjectSP(new CommandObjectThreadJump(interpreter)));
2736 LoadSubCommand("select",
2737 CommandObjectSP(new CommandObjectThreadSelect(interpreter)));
2738 LoadSubCommand("until",
2739 CommandObjectSP(new CommandObjectThreadUntil(interpreter)));
2740 LoadSubCommand("info",
2741 CommandObjectSP(new CommandObjectThreadInfo(interpreter)));
2743 interpreter)));
2744 LoadSubCommand("siginfo",
2746 LoadSubCommand("step-in",
2748 interpreter, "thread step-in",
2749 "Source level single step, stepping into calls. Defaults "
2750 "to current thread unless specified.",
2751 nullptr, eStepTypeInto)));
2752
2753 LoadSubCommand("step-out",
2755 interpreter, "thread step-out",
2756 "Finish executing the current stack frame and stop after "
2757 "returning. Defaults to current thread unless specified.",
2758 nullptr, eStepTypeOut)));
2759
2760 LoadSubCommand("step-over",
2762 interpreter, "thread step-over",
2763 "Source level single step, stepping over calls. Defaults "
2764 "to current thread unless specified.",
2765 nullptr, eStepTypeOver)));
2766
2767 LoadSubCommand("step-inst",
2769 interpreter, "thread step-inst",
2770 "Instruction level single step, stepping into calls. "
2771 "Defaults to current thread unless specified.",
2772 nullptr, eStepTypeTrace)));
2773
2774 LoadSubCommand("step-inst-over",
2776 interpreter, "thread step-inst-over",
2777 "Instruction level single step, stepping over calls. "
2778 "Defaults to current thread unless specified.",
2779 nullptr, eStepTypeTraceOver)));
2780
2782 "step-scripted",
2784 interpreter, "thread step-scripted",
2785 "Step as instructed by the script class passed in the -C option. "
2786 "You can also specify a dictionary of key (-k) and value (-v) pairs "
2787 "that will be used to populate an SBStructuredData Dictionary, which "
2788 "will be passed to the constructor of the class implementing the "
2789 "scripted step. See the Python Reference for more details.",
2790 nullptr, eStepTypeScripted)));
2791
2793 interpreter)));
2794 LoadSubCommand("trace",
2796}
2797
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:490
static void skip(TSLexer *lexer)
~CommandObjectMultiwordThreadPlan() override=default
CommandObjectMultiwordThreadPlan(CommandInterpreter &interpreter)
~CommandObjectMultiwordTraceDump() override=default
CommandObjectMultiwordTraceDump(CommandInterpreter &interpreter)
CommandObjectMultiwordTrace(CommandInterpreter &interpreter)
~CommandObjectMultiwordTrace() override=default
void OptionParsingStarting(ExecutionContext *execution_context) override
Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, ExecutionContext *execution_context) override
Set the value of an option.
llvm::ArrayRef< OptionDefinition > GetDefinitions() override
CommandObjectThreadBacktrace(CommandInterpreter &interpreter)
std::optional< std::string > GetRepeatCommand(Args &current_args, uint32_t index) override
Get the command that appropriate for a "repeat" of the current command.
void DoExtendedBacktrace(Thread *thread, CommandReturnObject &result)
bool HandleOneThread(lldb::tid_t tid, CommandReturnObject &result) override
~CommandObjectThreadBacktrace() override=default
~CommandObjectThreadContinue() override=default
void DoExecute(Args &command, CommandReturnObject &result) override
CommandObjectThreadContinue(CommandInterpreter &interpreter)
CommandObjectThreadException(CommandInterpreter &interpreter)
bool HandleOneThread(lldb::tid_t tid, CommandReturnObject &result) override
~CommandObjectThreadException() override=default
void HandleArgumentCompletion(CompletionRequest &request, OptionElementVector &opt_element_vector) override
The default version handles argument definitions that have only one argument type,...
llvm::ArrayRef< OptionDefinition > GetDefinitions() override
void OptionParsingStarting(ExecutionContext *execution_context) override
Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, ExecutionContext *execution_context) override
Set the value of an option.
void HandleArgumentCompletion(CompletionRequest &request, OptionElementVector &opt_element_vector) override
The default version handles argument definitions that have only one argument type,...
CommandObjectThreadInfo(CommandInterpreter &interpreter)
bool HandleOneThread(lldb::tid_t tid, CommandReturnObject &result) override
~CommandObjectThreadInfo() override=default
Options * GetOptions() override
Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, ExecutionContext *execution_context) override
Set the value of an option.
llvm::ArrayRef< OptionDefinition > GetDefinitions() override
void OptionParsingStarting(ExecutionContext *execution_context) override
CommandObjectThreadJump(CommandInterpreter &interpreter)
void DoExecute(Args &args, CommandReturnObject &result) override
~CommandObjectThreadJump() override=default
Options * GetOptions() override
void DoExecute(Args &command, CommandReturnObject &result) override
~CommandObjectThreadList() override=default
CommandObjectThreadList(CommandInterpreter &interpreter)
void DoExecute(Args &args, CommandReturnObject &result) override
CommandObjectThreadPlanDiscard(CommandInterpreter &interpreter)
~CommandObjectThreadPlanDiscard() override=default
void HandleArgumentCompletion(CompletionRequest &request, OptionElementVector &opt_element_vector) override
The default version handles argument definitions that have only one argument type,...
llvm::ArrayRef< OptionDefinition > GetDefinitions() override
Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, ExecutionContext *execution_context) override
Set the value of an option.
void OptionParsingStarting(ExecutionContext *execution_context) override
CommandObjectThreadPlanList(CommandInterpreter &interpreter)
bool HandleOneThread(lldb::tid_t tid, CommandReturnObject &result) override
~CommandObjectThreadPlanList() override=default
void DoExecute(Args &command, CommandReturnObject &result) override
CommandObjectThreadPlanPrune(CommandInterpreter &interpreter)
~CommandObjectThreadPlanPrune() override=default
void DoExecute(Args &args, CommandReturnObject &result) override
Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, ExecutionContext *execution_context) override
Set the value of an option.
void OptionParsingStarting(ExecutionContext *execution_context) override
llvm::ArrayRef< OptionDefinition > GetDefinitions() override
CommandObjectThreadReturn(CommandInterpreter &interpreter)
void DoExecute(llvm::StringRef command, CommandReturnObject &result) override
~CommandObjectThreadReturn() override=default
Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, ExecutionContext *execution_context) override
void OptionParsingStarting(ExecutionContext *execution_context) override
llvm::ArrayRef< OptionDefinition > GetDefinitions() override
void DoExecute(Args &command, CommandReturnObject &result) override
void HandleArgumentCompletion(CompletionRequest &request, OptionElementVector &opt_element_vector) override
The default version handles argument definitions that have only one argument type,...
CommandObjectThreadSelect(CommandInterpreter &interpreter)
~CommandObjectThreadSelect() override=default
OptionGroupThreadSelect m_options
~CommandObjectThreadSiginfo() override=default
bool HandleOneThread(lldb::tid_t tid, CommandReturnObject &result) override
CommandObjectThreadSiginfo(CommandInterpreter &interpreter)
void HandleArgumentCompletion(CompletionRequest &request, OptionElementVector &opt_element_vector) override
The default version handles argument definitions that have only one argument type,...
OptionGroupPythonClassWithDict m_class_options
~CommandObjectThreadStepWithTypeAndScope() override=default
void DoExecute(Args &command, CommandReturnObject &result) override
void HandleArgumentCompletion(CompletionRequest &request, OptionElementVector &opt_element_vector) override
The default version handles argument definitions that have only one argument type,...
CommandObjectThreadStepWithTypeAndScope(CommandInterpreter &interpreter, const char *name, const char *help, const char *syntax, StepType step_type)
llvm::ArrayRef< OptionDefinition > GetDefinitions() override
Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, ExecutionContext *execution_context) override
Set the value of an option.
void OptionParsingStarting(ExecutionContext *execution_context) override
CommandObjectThreadUntil(CommandInterpreter &interpreter)
~CommandObjectThreadUntil() override=default
void DoExecute(Args &command, CommandReturnObject &result) override
llvm::ArrayRef< OptionDefinition > GetDefinitions() override
void OptionParsingStarting(ExecutionContext *execution_context) override
Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, ExecutionContext *execution_context) override
Set the value of an option.
void DoExecute(Args &args, CommandReturnObject &result) override
CommandObjectTraceDumpFunctionCalls(CommandInterpreter &interpreter)
~CommandObjectTraceDumpFunctionCalls() override=default
Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, ExecutionContext *execution_context) override
Set the value of an option.
void OptionParsingStarting(ExecutionContext *execution_context) override
llvm::ArrayRef< OptionDefinition > GetDefinitions() override
~CommandObjectTraceDumpInfo() override=default
bool HandleOneThread(lldb::tid_t tid, CommandReturnObject &result) override
CommandObjectTraceDumpInfo(CommandInterpreter &interpreter)
llvm::ArrayRef< OptionDefinition > GetDefinitions() override
Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, ExecutionContext *execution_context) override
Set the value of an option.
void OptionParsingStarting(ExecutionContext *execution_context) override
CommandObjectTraceDumpInstructions(CommandInterpreter &interpreter)
~CommandObjectTraceDumpInstructions() override=default
std::optional< std::string > GetRepeatCommand(Args &current_command_args, uint32_t index) override
Get the command that appropriate for a "repeat" of the current command.
void DoExecute(Args &args, CommandReturnObject &result) override
std::optional< lldb::user_id_t > m_last_id
CommandObjectTraceExport(CommandInterpreter &interpreter)
lldb::CommandObjectSP GetDelegateCommand(Trace &trace) override
CommandObjectTraceStart(CommandInterpreter &interpreter)
~CommandObjectTraceStop() override=default
bool DoExecuteOnThreads(Args &command, CommandReturnObject &result, llvm::ArrayRef< lldb::tid_t > tids) override
CommandObjectTraceStop(CommandInterpreter &interpreter)
void OptionParsingStarting(ExecutionContext *execution_context) override
~ThreadStepScopeOptionGroup() override=default
Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, ExecutionContext *execution_context) override
llvm::ArrayRef< OptionDefinition > GetDefinitions() override
A section + offset based address range class.
Address & GetBaseAddress()
Get accessor for the base address of the range.
lldb::addr_t GetByteSize() const
Get accessor for the byte size of this range.
A section + offset based address class.
Definition Address.h:62
lldb::addr_t GetLoadAddress(Target *target) const
Get the load address.
Definition Address.cpp:301
lldb::addr_t GetCallableLoadAddress(Target *target, bool is_indirect=false) const
Get the load address as a callable code load address.
Definition Address.cpp:326
lldb::addr_t GetFileAddress() const
Get the file address.
Definition Address.cpp:281
bool IsValid() const
Check if the object state is valid.
Definition Address.h:355
A command line argument class.
Definition Args.h:33
size_t GetArgumentCount() const
Gets the number of arguments left in this command object.
Definition Args.h:120
void ReplaceArgumentAtIndex(size_t idx, llvm::StringRef arg_str, char quote_char='\0')
Replaces the argument value at index idx to arg_str if idx is a valid argument index.
Definition Args.cpp:347
void AppendArgument(llvm::StringRef arg_str, char quote_char='\0')
Appends a new argument to the end of the list argument list.
Definition Args.cpp:332
llvm::ArrayRef< ArgEntry > entries() const
Definition Args.h:132
const char * GetArgumentAtIndex(size_t idx) const
Gets the NULL terminated C string argument pointer for the argument at index idx.
Definition Args.cpp:273
bool GetCommandString(std::string &command) const
Definition Args.cpp:215
bool GetQuotedCommandString(std::string &command) const
Definition Args.cpp:232
A class that describes a single lexical block.
Definition Block.h:41
bool GetRangeContainingAddress(const Address &addr, AddressRange &range)
Definition Block.cpp:248
static bool InvokeCommonCompletionCallbacks(CommandInterpreter &interpreter, uint32_t completion_mask, lldb_private::CompletionRequest &request, SearchFilter *searcher)
CommandObjectIterateOverThreads(CommandInterpreter &interpreter, const char *name, const char *help, const char *syntax, uint32_t flags)
void DoExecute(Args &command, CommandReturnObject &result) override
CommandObjectMultipleThreads(CommandInterpreter &interpreter, const char *name, const char *help, const char *syntax, uint32_t flags)
CommandObjectMultiwordThread(CommandInterpreter &interpreter)
bool LoadSubCommand(llvm::StringRef cmd_name, const lldb::CommandObjectSP &command_obj) override
CommandObjectMultiword(CommandInterpreter &interpreter, const char *name, const char *help=nullptr, const char *syntax=nullptr, uint32_t flags=0)
CommandObjectParsed(CommandInterpreter &interpreter, const char *name, const char *help=nullptr, const char *syntax=nullptr, uint32_t flags=0)
CommandObjectRaw(CommandInterpreter &interpreter, llvm::StringRef name, llvm::StringRef help="", llvm::StringRef syntax="", uint32_t flags=0)
CommandObjectTraceProxy(bool live_debug_session_only, CommandInterpreter &interpreter, const char *name, const char *help=nullptr, const char *syntax=nullptr, uint32_t flags=0)
std::vector< CommandArgumentData > CommandArgumentEntry
void AddSimpleArgumentList(lldb::CommandArgumentType arg_type, ArgumentRepetitionType repetition_type=eArgRepeatPlain)
std::vector< CommandArgumentEntry > m_arguments
CommandInterpreter & GetCommandInterpreter()
CommandInterpreter & m_interpreter
virtual void HandleArgumentCompletion(CompletionRequest &request, OptionElementVector &opt_element_vector)
The default version handles argument definitions that have only one argument type,...
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:396
void SetUseDynamic(lldb::DynamicValueType dynamic=lldb::eDynamicCanRunTarget)
Definition Target.h:411
"lldb/Target/ExecutionContext.h" A class that contains an execution context.
const lldb::TargetSP & GetTargetSP() const
Get accessor to get the target shared pointer.
const lldb::ProcessSP & GetProcessSP() const
Get accessor to get the process shared pointer.
Process & GetProcessRef() const
Returns a reference to the process object.
const lldb::ThreadSP & GetThreadSP() const
Get accessor to get the thread shared pointer.
A file collection class.
A file utility class.
Definition FileSpec.h:57
bool GetRangeContainingLoadAddress(lldb::addr_t load_addr, Target &target, AddressRange &range)
Definition Function.h:447
AddressRanges GetAddressRanges()
Definition Function.h:440
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:357
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:540
ThreadList & GetThreadList()
Definition Process.h:2380
Status Resume()
Resumes all of a process's threads as configured using the Thread run control functions.
Definition Process.cpp:1332
void PruneThreadPlans()
Prune ThreadPlanStacks for all unreported threads.
Definition Process.cpp:1222
bool PruneThreadPlansForTID(lldb::tid_t tid)
Prune ThreadPlanStacks for unreported threads.
Definition Process.cpp:1218
virtual SystemRuntime * GetSystemRuntime()
Get the system runtime plug-in for this process.
Definition Process.cpp:3114
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:1226
Status ResumeSynchronous(Stream *stream)
Resume a process, and wait for it to stop.
Definition Process.cpp:1349
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:6199
lldb::StateType GetState()
Get accessor for the current process state.
Definition Process.cpp:1278
uint32_t GetIOHandlerID() const
Definition Process.h:2442
void GetStatus(Stream &ostrm, bool is_verbose=false)
Definition Process.cpp:6176
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:667
uint32_t FindEntryIndexThatContains(B addr) const
Definition RangeMap.h:316
BaseType GetMaxRangeEnd(BaseType fail_value) const
Definition RangeMap.h:272
void Append(const Entry &entry)
Definition RangeMap.h:179
BaseType GetMinRangeBase(BaseType fail_value) const
Definition RangeMap.h:261
Process * GetProcess()
Definition Runtime.h:22
This base class provides an interface to stack frames.
Definition StackFrame.h:44
virtual const SymbolContext & GetSymbolContext(lldb::SymbolContextItem resolve_scope)
Provide a SymbolContext for this StackFrame's current pc value.
virtual bool HasDebugInformation()
Determine whether this StackFrame has debug information available or not.
virtual const Address & GetFrameCodeAddress()
Get an Address for the current pc value in this StackFrame.
An error handling class.
Definition Status.h:118
static Status FromErrorStringWithFormat(const char *format,...) __attribute__((format(printf
Definition Status.cpp:106
static Status FromErrorString(const char *str)
Definition Status.h:141
bool Fail() const
Test for error condition.
Definition Status.cpp:293
llvm::StringRef GetString() const
A stream class that can stream formatted output to a file.
Definition Stream.h:28
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
Definition Stream.cpp:134
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:2907
uint32_t GetSize(bool can_update=true)
bool SetSelectedThreadByID(lldb::tid_t tid, bool notify=false)
lldb::ThreadSP FindThreadByIndexID(uint32_t index_id, bool can_update=true)
lldb::ThreadSP GetThreadAtIndex(uint32_t idx, bool can_update=true)
std::recursive_mutex & GetMutex() const override
lldb::ThreadSP FindThreadByID(lldb::tid_t tid, bool can_update=true)
Class used to dump the instructions of a TraceCursor using its current state and granularity.
Definition TraceDumper.h:51
std::optional< lldb::user_id_t > DumpInstructions(size_t count)
Dump count instructions of the thread trace starting at the current cursor position.
void DumpFunctionCalls()
Dump all function calls forwards chronologically and hierarchically.
A plug-in interface definition class for trace information.
Definition Trace.h:48
virtual lldb::CommandObjectSP GetThreadTraceStartCommand(CommandInterpreter &interpreter)=0
Get the command handle for the "thread trace start" command.
#define LLDB_OPT_SET_1
#define LLDB_OPT_SET_2
#define LLDB_INVALID_LINE_NUMBER
#define LLDB_INVALID_THREAD_ID
#define LLDB_INVALID_INDEX32
#define LLDB_OPT_SET_ALL
#define LLDB_INVALID_ADDRESS
#define UINT32_MAX
#define LLDB_INVALID_FRAME_ID
@ DoNoSelectMostRelevantFrame
A class that represents a running process on the host machine.
std::vector< OptionArgElement > OptionElementVector
Definition Options.h:43
const char * StateAsCString(lldb::StateType state)
Converts a StateType to a C string.
Definition State.cpp:14
std::string toString(FormatterBytecode::OpCodes op)
@ eStepTypeTraceOver
Single step one instruction, stepping over.
@ eStepTypeOut
Single step out a specified context.
@ eStepTypeScripted
A step type implemented by the script interpreter.
@ eStepTypeInto
Single step into a specified context.
@ eStepTypeOver
Single step over a specified context.
@ eStepTypeTrace
Single step one instruction.
@ eThreadIndexCompletion
std::shared_ptr< lldb_private::Trace > TraceSP
std::shared_ptr< lldb_private::ThreadPlan > ThreadPlanSP
std::shared_ptr< lldb_private::StackFrame > StackFrameSP
DescriptionLevel
Description levels for "void GetDescription(Stream *, DescriptionLevel)" calls.
@ eDescriptionLevelFull
@ eDescriptionLevelVerbose
std::shared_ptr< lldb_private::Thread > ThreadSP
std::shared_ptr< lldb_private::CommandObject > CommandObjectSP
std::shared_ptr< lldb_private::ValueObject > ValueObjectSP
StateType
Process and Thread States.
@ eStateStopped
Process or thread is stopped and can be examined.
@ eStateSuspended
Process or thread is in a suspended state as far as the debugger is concerned while other processes o...
@ eStateRunning
Process or thread is running and can't be examined.
@ eStateCrashed
Process or thread has crashed and can be examined.
ExpressionResults
The results of expression evaluation.
@ eExpressionCompleted
@ eExpressionSetupError
std::shared_ptr< lldb_private::Process > ProcessSP
@ 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
uint64_t addr_t
Definition lldb-types.h:80
std::shared_ptr< lldb_private::Target > TargetSP
RunMode
Thread Run Modes.
@ eOnlyDuringStepping
uint64_t tid_t
Definition lldb-types.h:84
std::shared_ptr< lldb_private::StackFrameList > StackFrameListSP
uint32_t frame_list_id_t
Definition lldb-types.h:86
Used to build individual command argument lists.
uint32_t arg_opt_set_association
This arg might be associated only with some particular option set(s).
A line table entry class.
Definition LineEntry.h:21
AddressRange range
The section offset address range for this line entry.
Definition LineEntry.h:137
uint32_t line
The source line number, or LLDB_INVALID_LINE_NUMBER if there is no line number information.
Definition LineEntry.h:151
const FileSpec & GetFile() const
Helper to access the file.
Definition LineEntry.h:134
static int64_t ToOptionEnum(llvm::StringRef s, const OptionEnumValues &enum_values, int32_t fail_value, Status &error)
static lldb::addr_t ToAddress(const ExecutionContext *exe_ctx, llvm::StringRef s, lldb::addr_t fail_value, Status *error_ptr)
Try to parse an address.
static bool ToBoolean(llvm::StringRef s, bool fail_value, bool *success_ptr)
Class that holds the configuration used by TraceDumper for traversing and dumping instructions.
Definition TraceDumper.h:21
lldb::user_id_t GetID() const
Get accessor for the user ID.
Definition UserID.h:47