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