LLDB mainline
CommandObjectTarget.cpp
Go to the documentation of this file.
1//===-- CommandObjectTarget.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 "lldb/Core/Address.h"
12#include "lldb/Core/Debugger.h"
13#include "lldb/Core/IOHandler.h"
14#include "lldb/Core/Module.h"
17#include "lldb/Core/Section.h"
43#include "lldb/Target/ABI.h"
44#include "lldb/Target/Process.h"
48#include "lldb/Target/Thread.h"
50#include "lldb/Utility/Args.h"
55#include "lldb/Utility/State.h"
56#include "lldb/Utility/Stream.h"
58#include "lldb/Utility/Timer.h"
61#include "lldb/lldb-forward.h"
63
64#include "llvm/ADT/ScopeExit.h"
65#include "llvm/ADT/StringRef.h"
66#include "llvm/Support/FileSystem.h"
67#include "llvm/Support/FormatAdapters.h"
68
69using namespace lldb;
70using namespace lldb_private;
71
72static void DumpTargetInfo(uint32_t target_idx, Target *target,
73 const char *prefix_cstr,
74 bool show_stopped_process_status, Stream &strm) {
75 const ArchSpec &target_arch = target->GetArchitecture();
76
77 Module *exe_module = target->GetExecutableModulePointer();
78 char exe_path[PATH_MAX];
79 bool exe_valid = false;
80 if (exe_module)
81 exe_valid = exe_module->GetFileSpec().GetPath(exe_path, sizeof(exe_path));
82
83 if (!exe_valid)
84 ::strcpy(exe_path, "<none>");
85
86 std::string formatted_label = "";
87 const std::string &label = target->GetLabel();
88 if (!label.empty()) {
89 formatted_label = " (" + label + ")";
90 }
91
92 strm.Printf("%starget #%u%s: %s", prefix_cstr ? prefix_cstr : "", target_idx,
93 formatted_label.data(), exe_path);
94
95 uint32_t properties = 0;
96 if (target_arch.IsValid()) {
97 strm.PutCString(" ( arch=");
98 target_arch.DumpTriple(strm.AsRawOstream());
99 properties++;
100 }
101 PlatformSP platform_sp(target->GetPlatform());
102 if (platform_sp)
103 strm.Format("{0}platform={1}", properties++ > 0 ? ", " : " ( ",
104 platform_sp->GetName());
105
106 ProcessSP process_sp(target->GetProcessSP());
107 bool show_process_status = false;
108 if (process_sp) {
109 lldb::pid_t pid = process_sp->GetID();
110 StateType state = process_sp->GetState();
111 if (show_stopped_process_status)
112 show_process_status = StateIsStoppedState(state, true);
113 const char *state_cstr = StateAsCString(state);
114 if (pid != LLDB_INVALID_PROCESS_ID)
115 strm.Printf("%spid=%" PRIu64, properties++ > 0 ? ", " : " ( ", pid);
116 strm.Printf("%sstate=%s", properties++ > 0 ? ", " : " ( ", state_cstr);
117 }
118 if (properties > 0)
119 strm.PutCString(" )\n");
120 else
121 strm.EOL();
122 if (show_process_status) {
123 const bool only_threads_with_stop_reason = true;
124 const uint32_t start_frame = 0;
125 const uint32_t num_frames = 1;
126 const uint32_t num_frames_with_source = 1;
127 const bool stop_format = false;
128 process_sp->GetStatus(strm);
129 process_sp->GetThreadStatus(strm, only_threads_with_stop_reason,
130 start_frame, num_frames, num_frames_with_source,
131 stop_format);
132 }
133}
134
135static uint32_t DumpTargetList(TargetList &target_list,
136 bool show_stopped_process_status, Stream &strm) {
137 const uint32_t num_targets = target_list.GetNumTargets();
138 if (num_targets) {
139 TargetSP selected_target_sp(target_list.GetSelectedTarget());
140 strm.PutCString("Current targets:\n");
141 for (uint32_t i = 0; i < num_targets; ++i) {
142 TargetSP target_sp(target_list.GetTargetAtIndex(i));
143 if (target_sp) {
144 bool is_selected = target_sp.get() == selected_target_sp.get();
145 DumpTargetInfo(i, target_sp.get(), is_selected ? "* " : " ",
146 show_stopped_process_status, strm);
147 }
148 }
149 }
150 return num_targets;
151}
152
153#define LLDB_OPTIONS_target_dependents
154#include "CommandOptions.inc"
155
157public:
159
160 ~OptionGroupDependents() override = default;
161
162 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
163 return llvm::ArrayRef(g_target_dependents_options);
164 }
165
166 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value,
167 ExecutionContext *execution_context) override {
169
170 // For compatibility no value means don't load dependents.
171 if (option_value.empty()) {
173 return error;
174 }
175
176 const char short_option =
177 g_target_dependents_options[option_idx].short_option;
178 if (short_option == 'd') {
179 LoadDependentFiles tmp_load_dependents;
181 option_value, g_target_dependents_options[option_idx].enum_values, 0,
182 error);
183 if (error.Success())
184 m_load_dependent_files = tmp_load_dependents;
185 } else {
187 "unrecognized short option '%c'", short_option);
188 }
189
190 return error;
191 }
192
193 Status SetOptionValue(uint32_t, const char *, ExecutionContext *) = delete;
194
198
200
201private:
205};
206
207#pragma mark CommandObjectTargetCreate
208
210public:
213 interpreter, "target create",
214 "Create a target using the argument as the main executable.",
215 nullptr),
216 m_platform_options(true), // Include the --platform option.
217 m_core_file(LLDB_OPT_SET_1, false, "core", 'c', 0, eArgTypeFilename,
218 "Fullpath to a core file to use for this target."),
219 m_label(LLDB_OPT_SET_1, false, "label", 'l', 0, eArgTypeName,
220 "Optional name for this target.", nullptr),
221 m_symbol_file(LLDB_OPT_SET_1, false, "symfile", 's', 0,
223 "Fullpath to a stand alone debug "
224 "symbols file for when debug symbols "
225 "are not in the executable."),
227 LLDB_OPT_SET_1, false, "remote-file", 'r', 0, eArgTypeFilename,
228 "Fullpath to the file on the remote host if debugging remotely.") {
229
231
239 m_option_group.Finalize();
240 }
241
242 ~CommandObjectTargetCreate() override = default;
243
244 Options *GetOptions() override { return &m_option_group; }
245
246protected:
247 void DoExecute(Args &command, CommandReturnObject &result) override {
248 const size_t argc = command.GetArgumentCount();
249 FileSpec core_file(m_core_file.GetOptionValue().GetCurrentValue());
250 FileSpec remote_file(m_remote_file.GetOptionValue().GetCurrentValue());
251
252 if (core_file) {
253 auto file = FileSystem::Instance().Open(
255
256 if (!file) {
257 result.AppendErrorWithFormatv("Cannot open '{0}': {1}.",
258 core_file.GetPath(),
259 llvm::toString(file.takeError()));
260 return;
261 }
262 }
263
264 if (argc == 1 || core_file || remote_file) {
265 FileSpec symfile(m_symbol_file.GetOptionValue().GetCurrentValue());
266 if (symfile) {
267 auto file = FileSystem::Instance().Open(
269
270 if (!file) {
271 result.AppendErrorWithFormatv("Cannot open '{0}': {1}.",
272 symfile.GetPath(),
273 llvm::toString(file.takeError()));
274 return;
275 }
276 }
277
278 const char *file_path = command.GetArgumentAtIndex(0);
279 LLDB_SCOPED_TIMERF("(lldb) target create '%s'", file_path);
280
281 bool must_set_platform_path = false;
282
283 Debugger &debugger = GetDebugger();
284
285 TargetSP target_sp;
286 llvm::StringRef arch_cstr = m_arch_option.GetArchitectureName();
288 debugger, file_path, arch_cstr,
289 m_add_dependents.m_load_dependent_files, &m_platform_options,
290 target_sp));
291
292 if (!target_sp) {
293 result.AppendError(error.AsCString());
294 return;
295 }
296
297 const llvm::StringRef label =
298 m_label.GetOptionValue().GetCurrentValueAsRef();
299 if (!label.empty()) {
300 if (auto E = target_sp->SetLabel(label))
301 result.SetError(std::move(E));
302 else
304 return;
305 }
306
307 llvm::scope_exit on_error(
308 [&target_list = debugger.GetTargetList(), &target_sp]() {
309 target_list.DeleteTarget(target_sp);
310 });
311
312 // Only get the platform after we create the target because we might
313 // have switched platforms depending on what the arguments were to
314 // CreateTarget() we can't rely on the selected platform.
315
316 PlatformSP platform_sp = target_sp->GetPlatform();
317
318 FileSpec file_spec;
319 if (file_path) {
320 file_spec.SetFile(file_path, FileSpec::Style::native);
321 FileSystem::Instance().Resolve(file_spec);
322
323 // Try to resolve the exe based on PATH and/or platform-specific
324 // suffixes, but only if using the host platform.
325 if (platform_sp && platform_sp->IsHost() &&
326 !FileSystem::Instance().Exists(file_spec))
328 }
329
330 if (remote_file) {
331 if (platform_sp) {
332 // I have a remote file.. two possible cases
333 if (file_spec && FileSystem::Instance().Exists(file_spec)) {
334 // if the remote file does not exist, push it there
335 if (!platform_sp->GetFileExists(remote_file)) {
336 Status err = platform_sp->PutFile(file_spec, remote_file);
337 if (err.Fail()) {
338 result.AppendError(err.AsCString());
339 return;
340 }
341 }
342 } else {
343 // there is no local file and we need one
344 // in order to make the remote ---> local transfer we need a
345 // platform
346 // TODO: if the user has passed in a --platform argument, use it
347 // to fetch the right platform
348 if (file_path) {
349 // copy the remote file to the local file
350 Status err = platform_sp->GetFile(remote_file, file_spec);
351 if (err.Fail()) {
352 result.AppendError(err.AsCString());
353 return;
354 }
355 } else {
356 // If the remote file exists, we can debug reading that out of
357 // memory. If the platform is already connected to an lldb-server
358 // then we can at least check the file exists remotely. Otherwise
359 // we'll just have to trust that it will be there when we do
360 // process connect.
361 // I don't do this for the host platform because it seems odd to
362 // support supplying a remote file but no local file for a local
363 // debug session.
364 if (platform_sp->IsHost()) {
365 result.AppendError("Supply a local file, not a remote file, "
366 "when debugging on the host.");
367 return;
368 }
369 if (platform_sp->IsConnected() && !platform_sp->GetFileExists(remote_file)) {
370 result.AppendError("remote --> local transfer without local "
371 "path is not implemented yet");
372 return;
373 }
374 // Since there's only a remote file, we need to set the executable
375 // file spec to the remote one.
376 ProcessLaunchInfo launch_info = target_sp->GetProcessLaunchInfo();
377 launch_info.SetExecutableFile(FileSpec(remote_file), true);
378 target_sp->SetProcessLaunchInfo(launch_info);
379 }
380 }
381 } else {
382 result.AppendError("no platform found for target");
383 return;
384 }
385 }
386
387 if (symfile || remote_file) {
388 ModuleSP module_sp(target_sp->GetExecutableModule());
389 if (module_sp) {
390 if (symfile)
391 module_sp->SetSymbolFileFileSpec(symfile);
392 if (remote_file) {
393 std::string remote_path = remote_file.GetPath();
394 target_sp->SetArg0(remote_path.c_str());
395 module_sp->SetPlatformFileSpec(remote_file);
396 }
397 }
398 }
399
400 if (must_set_platform_path) {
401 ModuleSpec main_module_spec(file_spec);
402 ModuleSP module_sp =
403 target_sp->GetOrCreateModule(main_module_spec, true /* notify */);
404 if (module_sp)
405 module_sp->SetPlatformFileSpec(remote_file);
406 }
407
408 if (core_file) {
409 FileSpec core_file_dir;
410 core_file_dir.SetDirectory(core_file.GetDirectory());
411 target_sp->AppendExecutableSearchPaths(core_file_dir);
412
413 ProcessSP process_sp(target_sp->CreateProcess(
414 GetDebugger().GetListener(), llvm::StringRef(), &core_file, false));
415
416 if (process_sp) {
417 // Seems weird that we Launch a core file, but that is what we
418 // do!
419 {
420 ElapsedTime load_core_time(
421 target_sp->GetStatistics().GetLoadCoreTime());
422 error = process_sp->LoadCore();
423 }
424
425 if (error.Fail()) {
426 result.AppendError(error.AsCString("unknown core file format"));
427 return;
428 } else {
430 "Core file '{0}' ({1}) was loaded.\n", core_file.GetPath(),
431 target_sp->GetArchitecture().GetArchitectureName());
432 if (auto core_args = process_sp->GetCoreFileArgs())
433 core_args->Format(result.GetOutputStream());
435 on_error.release();
436 }
437 } else {
438 result.AppendErrorWithFormatv("Unknown core file format '{0}'\n",
439 core_file.GetPath());
440 }
441 } else {
443 "Current executable set to '{0}' ({1}).",
444 file_spec.GetPath().c_str(),
445 target_sp->GetArchitecture().GetArchitectureName());
447 on_error.release();
448 }
449 } else {
450 result.AppendErrorWithFormat("'%s' takes exactly one executable path "
451 "argument, or use the --core option",
452 m_cmd_name.c_str());
453 }
454 }
455
456private:
465};
466
467#pragma mark CommandObjectTargetList
468
470public:
473 interpreter, "target list",
474 "List all current targets in the current debug session.", nullptr) {
475 }
476
477 ~CommandObjectTargetList() override = default;
478
479protected:
480 void DoExecute(Args &args, CommandReturnObject &result) override {
481 Stream &strm = result.GetOutputStream();
482
483 bool show_stopped_process_status = false;
484 if (DumpTargetList(GetDebugger().GetTargetList(),
485 show_stopped_process_status, strm) == 0) {
486 strm.PutCString("No targets.\n");
487 }
489 }
490};
491
492#pragma mark CommandObjectTargetSelect
493
495public:
498 interpreter, "target select",
499 "Select a target as the current target by target index.", nullptr) {
501 }
502
503 ~CommandObjectTargetSelect() override = default;
504
505protected:
506 void DoExecute(Args &args, CommandReturnObject &result) override {
507 if (args.GetArgumentCount() == 1) {
508 const char *target_identifier = args.GetArgumentAtIndex(0);
509 uint32_t target_idx = LLDB_INVALID_INDEX32;
510 TargetList &target_list = GetDebugger().GetTargetList();
511 const uint32_t num_targets = target_list.GetNumTargets();
512 if (llvm::to_integer(target_identifier, target_idx)) {
513 if (target_idx < num_targets) {
514 target_list.SetSelectedTarget(target_idx);
515 Stream &strm = result.GetOutputStream();
516 bool show_stopped_process_status = false;
517 DumpTargetList(target_list, show_stopped_process_status, strm);
519 } else {
520 if (num_targets > 0) {
522 "index %u is out of range, valid target indexes are 0 - %u",
523 target_idx, num_targets - 1);
524 } else {
526 "index %u is out of range since there are no active targets",
527 target_idx);
528 }
529 }
530 } else {
531 for (size_t i = 0; i < num_targets; i++) {
532 if (TargetSP target_sp = target_list.GetTargetAtIndex(i)) {
533 const std::string &label = target_sp->GetLabel();
534 if (!label.empty() && label == target_identifier) {
535 target_idx = i;
536 break;
537 }
538 }
539 }
540
541 if (target_idx != LLDB_INVALID_INDEX32) {
542 target_list.SetSelectedTarget(target_idx);
543 Stream &strm = result.GetOutputStream();
544 bool show_stopped_process_status = false;
545 DumpTargetList(target_list, show_stopped_process_status, strm);
547 } else {
548 result.AppendErrorWithFormat("invalid index string value '%s'",
549 target_identifier);
550 }
551 }
552 } else {
553 result.AppendError(
554 "'target select' takes a single argument: a target index\n");
555 }
556 }
557};
558
559#pragma mark CommandObjectTargetDelete
560
562public:
564 : CommandObjectParsed(interpreter, "target delete",
565 "Delete one or more targets by target index.",
566 nullptr),
567 m_all_option(LLDB_OPT_SET_1, false, "all", 'a', "Delete all targets.",
568 false, true),
570 LLDB_OPT_SET_1, false, "clean", 'c',
571 "Perform extra cleanup to minimize memory consumption after "
572 "deleting the target. "
573 "By default, LLDB will keep in memory any modules previously "
574 "loaded by the target as well "
575 "as all of its debug info. Specifying --clean will unload all of "
576 "these shared modules and "
577 "cause them to be reparsed again the next time the target is run",
578 false, true) {
581 m_option_group.Finalize();
583 }
584
585 ~CommandObjectTargetDelete() override = default;
586
587 Options *GetOptions() override { return &m_option_group; }
588
589protected:
590 void DoExecute(Args &args, CommandReturnObject &result) override {
591 const size_t argc = args.GetArgumentCount();
592 std::vector<TargetSP> delete_target_list;
593 TargetList &target_list = GetDebugger().GetTargetList();
594 TargetSP target_sp;
595
596 if (m_all_option.GetOptionValue()) {
597 for (size_t i = 0; i < target_list.GetNumTargets(); ++i)
598 delete_target_list.push_back(target_list.GetTargetAtIndex(i));
599 } else if (argc > 0) {
600 const uint32_t num_targets = target_list.GetNumTargets();
601 // Bail out if don't have any targets.
602 if (num_targets == 0) {
603 result.AppendError("no targets to delete");
604 return;
605 }
606
607 for (auto &entry : args.entries()) {
608 uint32_t target_idx;
609 if (entry.ref().getAsInteger(0, target_idx)) {
610 result.AppendErrorWithFormat("invalid target index '%s'",
611 entry.c_str());
612 return;
613 }
614 if (target_idx < num_targets) {
615 target_sp = target_list.GetTargetAtIndex(target_idx);
616 if (target_sp) {
617 delete_target_list.push_back(target_sp);
618 continue;
619 }
620 }
621 if (num_targets > 1)
622 result.AppendErrorWithFormat("target index %u is out of range, valid "
623 "target indexes are 0 - %u",
624 target_idx, num_targets - 1);
625 else
627 "target index %u is out of range, the only valid index is 0",
628 target_idx);
629
630 return;
631 }
632 } else {
633 target_sp = target_list.GetSelectedTarget();
634 if (!target_sp) {
635 result.AppendErrorWithFormat("no target is currently selected");
636 return;
637 }
638 delete_target_list.push_back(target_sp);
639 }
640
641 const size_t num_targets_to_delete = delete_target_list.size();
642 for (size_t idx = 0; idx < num_targets_to_delete; ++idx) {
643 target_sp = delete_target_list[idx];
644 target_list.DeleteTarget(target_sp);
645 target_sp->Destroy();
646 }
647 // If "--clean" was specified, prune any orphaned shared modules from the
648 // global shared module list
649 if (m_cleanup_option.GetOptionValue()) {
650 const bool mandatory = true;
652 }
653 result.GetOutputStream().Printf("%u targets deleted.\n",
654 (uint32_t)num_targets_to_delete);
656 }
657
661};
662
664public:
667 interpreter, "target show-launch-environment",
668 "Shows the environment being passed to the process when launched, "
669 "taking info account 3 settings: target.env-vars, "
670 "target.inherit-env and target.unset-env-vars.",
671 nullptr, eCommandRequiresTarget) {}
672
674
675protected:
676 void DoExecute(Args &args, CommandReturnObject &result) override {
677 Target *target = m_exe_ctx.GetTargetPtr();
678 Environment env = target->GetEnvironment();
679
680 std::vector<Environment::value_type *> env_vector;
681 env_vector.reserve(env.size());
682 for (auto &KV : env)
683 env_vector.push_back(&KV);
684 std::sort(env_vector.begin(), env_vector.end(),
685 [](Environment::value_type *a, Environment::value_type *b) {
686 return a->first() < b->first();
687 });
688
689 auto &strm = result.GetOutputStream();
690 for (auto &KV : env_vector)
691 strm.Format("{0}={1}\n", KV->first(), KV->second);
692
694 }
695};
696
697#pragma mark CommandObjectTargetVariable
698
700 static const uint32_t SHORT_OPTION_FILE = 0x66696c65; // 'file'
701 static const uint32_t SHORT_OPTION_SHLB = 0x73686c62; // 'shlb'
702
703public:
705 : CommandObjectParsed(interpreter, "target variable",
706 "Read global variables for the current target, "
707 "before or while running a process.",
708 nullptr, eCommandRequiresTarget),
709 m_option_variable(false), // Don't include frame options
713 "A basename or fullpath to a file that contains "
714 "global variables. This option can be "
715 "specified multiple times."),
717 LLDB_OPT_SET_1, false, "shlib", SHORT_OPTION_SHLB, 0,
719 "A basename or fullpath to a shared library to use in the search "
720 "for global "
721 "variables. This option can be specified multiple times.") {
723
734 m_option_group.Finalize();
735 }
736
737 ~CommandObjectTargetVariable() override = default;
738
739 void DumpValueObject(Stream &s, VariableSP &var_sp, ValueObjectSP &valobj_sp,
740 const char *root_name) {
741 DumpValueObjectOptions options(m_varobj_options.GetAsDumpOptions());
742
743 if (!valobj_sp->GetTargetSP()->GetDisplayRuntimeSupportValues() &&
744 valobj_sp->IsRuntimeSupportValue())
745 return;
746
747 switch (var_sp->GetScope()) {
749 if (m_option_variable.show_scope)
750 s.PutCString("GLOBAL: ");
751 break;
752
754 if (m_option_variable.show_scope)
755 s.PutCString("STATIC: ");
756 break;
757
759 if (m_option_variable.show_scope)
760 s.PutCString(" ARG: ");
761 break;
762
764 if (m_option_variable.show_scope)
765 s.PutCString(" LOCAL: ");
766 break;
767
769 if (m_option_variable.show_scope)
770 s.PutCString("THREAD: ");
771 break;
772
773 default:
774 break;
775 }
776
777 if (m_option_variable.show_decl) {
778 bool show_fullpaths = false;
779 bool show_module = true;
780 if (var_sp->DumpDeclaration(&s, show_fullpaths, show_module))
781 s.PutCString(": ");
782 }
783
784 const Format format = m_option_format.GetFormat();
785 if (format != eFormatDefault)
786 options.SetFormat(format);
787
788 options.SetRootValueObjectName(root_name);
789
790 if (llvm::Error error = valobj_sp->Dump(s, options))
791 s << "error: " << toString(std::move(error));
792 }
793
794 static size_t GetVariableCallback(void *baton, const char *name,
795 VariableList &variable_list) {
796 size_t old_size = variable_list.GetSize();
797 Target *target = static_cast<Target *>(baton);
798 if (target)
800 variable_list);
801 return variable_list.GetSize() - old_size;
802 }
803
804 Options *GetOptions() override { return &m_option_group; }
805
806protected:
808 const SymbolContext &sc,
809 const VariableList &variable_list,
810 CommandReturnObject &result) {
811 Stream &s = result.GetOutputStream();
812 if (variable_list.Empty())
813 return;
814 if (sc.module_sp) {
815 if (sc.comp_unit) {
816 s.Format("Global variables for {0} in {1}:\n",
817 sc.comp_unit->GetPrimaryFile(), sc.module_sp->GetFileSpec());
818 } else {
819 s.Printf("Global variables for %s\n",
820 sc.module_sp->GetFileSpec().GetPath().c_str());
821 }
822 } else if (sc.comp_unit) {
823 s.Format("Global variables for {0}\n", sc.comp_unit->GetPrimaryFile());
824 }
825
826 for (VariableSP var_sp : variable_list) {
827 if (!var_sp)
828 continue;
830 exe_ctx.GetBestExecutionContextScope(), var_sp));
831
832 if (valobj_sp) {
833 result.GetValueObjectList().Append(valobj_sp);
834 DumpValueObject(s, var_sp, valobj_sp, var_sp->GetName().GetCString());
835 }
836 }
837 }
838
839 void DoExecute(Args &args, CommandReturnObject &result) override {
840 Target *target = m_exe_ctx.GetTargetPtr();
841 const size_t argc = args.GetArgumentCount();
842
843 if (argc > 0) {
844 for (const Args::ArgEntry &arg : args) {
845 VariableList variable_list;
846 ValueObjectList valobj_list;
847
848 size_t matches = 0;
849 bool use_var_name = false;
850 if (m_option_variable.use_regex) {
851 RegularExpression regex(arg.ref());
852 if (!regex.IsValid()) {
853 result.GetErrorStream().Printf(
854 "error: invalid regular expression: '%s'\n", arg.c_str());
855 return;
856 }
857 use_var_name = true;
859 variable_list);
860 matches = variable_list.GetSize();
861 } else {
863 arg.c_str(), m_exe_ctx.GetBestExecutionContextScope(),
864 GetVariableCallback, target, variable_list, valobj_list));
865 matches = variable_list.GetSize();
866 }
867
868 if (matches == 0) {
869 result.AppendErrorWithFormat("can't find global variable '%s'",
870 arg.c_str());
871 return;
872 } else {
873 for (uint32_t global_idx = 0; global_idx < matches; ++global_idx) {
874 VariableSP var_sp(variable_list.GetVariableAtIndex(global_idx));
875 if (var_sp) {
876 ValueObjectSP valobj_sp(
877 valobj_list.GetValueObjectAtIndex(global_idx));
878 if (!valobj_sp)
879 valobj_sp = ValueObjectVariable::Create(
880 m_exe_ctx.GetBestExecutionContextScope(), var_sp);
881
882 if (valobj_sp)
883 DumpValueObject(result.GetOutputStream(), var_sp, valobj_sp,
884 use_var_name ? var_sp->GetName().GetCString()
885 : arg.c_str());
886 }
887 }
888 }
889 }
890 } else {
891 const FileSpecList &compile_units =
892 m_option_compile_units.GetOptionValue().GetCurrentValue();
893 const FileSpecList &shlibs =
894 m_option_shared_libraries.GetOptionValue().GetCurrentValue();
895 SymbolContextList sc_list;
896 const size_t num_compile_units = compile_units.GetSize();
897 const size_t num_shlibs = shlibs.GetSize();
898 if (num_compile_units == 0 && num_shlibs == 0) {
899 bool success = false;
900 StackFrame *frame = m_exe_ctx.GetFramePtr();
901 CompileUnit *comp_unit = nullptr;
902 if (frame) {
903 SymbolContext sc = frame->GetSymbolContext(eSymbolContextCompUnit);
904 comp_unit = sc.comp_unit;
905 if (sc.comp_unit) {
906 const bool can_create = true;
907 VariableListSP comp_unit_varlist_sp(
908 sc.comp_unit->GetVariableList(can_create));
909 if (comp_unit_varlist_sp) {
910 size_t count = comp_unit_varlist_sp->GetSize();
911 if (count > 0) {
912 DumpGlobalVariableList(m_exe_ctx, sc, *comp_unit_varlist_sp,
913 result);
914 success = true;
915 }
916 }
917 }
918 }
919 if (!success) {
920 if (frame) {
921 if (comp_unit)
923 "no global variables in current compile unit: {0}\n",
924 comp_unit->GetPrimaryFile());
925 else
926 result.AppendErrorWithFormat("no debug information for frame %u",
927 frame->GetFrameIndex());
928 } else
929 result.AppendError("'target variable' takes one or more global "
930 "variable names as arguments\n");
931 }
932 } else {
933 SymbolContextList sc_list;
934 // We have one or more compile unit or shlib
935 if (num_shlibs > 0) {
936 for (size_t shlib_idx = 0; shlib_idx < num_shlibs; ++shlib_idx) {
937 const FileSpec module_file(shlibs.GetFileSpecAtIndex(shlib_idx));
938 ModuleSpec module_spec(module_file);
939
940 ModuleSP module_sp(
941 target->GetImages().FindFirstModule(module_spec));
942 if (module_sp) {
943 if (num_compile_units > 0) {
944 for (size_t cu_idx = 0; cu_idx < num_compile_units; ++cu_idx)
945 module_sp->FindCompileUnits(
946 compile_units.GetFileSpecAtIndex(cu_idx), sc_list);
947 } else {
948 SymbolContext sc;
949 sc.module_sp = module_sp;
950 sc_list.Append(sc);
951 }
952 } else {
953 // Didn't find matching shlib/module in target...
955 "target doesn't contain the specified shared library: %s",
956 module_file.GetPath().c_str());
957 }
958 }
959 } else {
960 // No shared libraries, we just want to find globals for the compile
961 // units files that were specified
962 for (size_t cu_idx = 0; cu_idx < num_compile_units; ++cu_idx)
963 target->GetImages().FindCompileUnits(
964 compile_units.GetFileSpecAtIndex(cu_idx), sc_list);
965 }
966
967 for (const SymbolContext &sc : sc_list) {
968 if (sc.comp_unit) {
969 const bool can_create = true;
970 VariableListSP comp_unit_varlist_sp(
971 sc.comp_unit->GetVariableList(can_create));
972 if (comp_unit_varlist_sp)
973 DumpGlobalVariableList(m_exe_ctx, sc, *comp_unit_varlist_sp,
974 result);
975 } else if (sc.module_sp) {
976 // Get all global variables for this module
977 lldb_private::RegularExpression all_globals_regex(
978 llvm::StringRef(".")); // Any global with at least one character
979 VariableList variable_list;
980 sc.module_sp->FindGlobalVariables(all_globals_regex, UINT32_MAX,
981 variable_list);
982 DumpGlobalVariableList(m_exe_ctx, sc, variable_list, result);
983 }
984 }
985 }
986 }
987
988 m_interpreter.PrintWarningsIfNecessary(result.GetOutputStream(),
989 m_cmd_name);
990 if (result.GetStatus() != eReturnStatusFailed)
992 }
993
1000};
1001
1002#pragma mark CommandObjectTargetModulesSearchPathsAdd
1003
1005public:
1007 : CommandObjectParsed(interpreter, "target modules search-paths add",
1008 "Add new image search paths substitution pairs to "
1009 "the current target.",
1010 nullptr, eCommandRequiresTarget) {
1012 CommandArgumentData old_prefix_arg;
1013 CommandArgumentData new_prefix_arg;
1014
1015 // Define the first variant of this arg pair.
1016 old_prefix_arg.arg_type = eArgTypeOldPathPrefix;
1017 old_prefix_arg.arg_repetition = eArgRepeatPairPlus;
1018
1019 // Define the first variant of this arg pair.
1020 new_prefix_arg.arg_type = eArgTypeNewPathPrefix;
1021 new_prefix_arg.arg_repetition = eArgRepeatPairPlus;
1022
1023 // There are two required arguments that must always occur together, i.e.
1024 // an argument "pair". Because they must always occur together, they are
1025 // treated as two variants of one argument rather than two independent
1026 // arguments. Push them both into the first argument position for
1027 // m_arguments...
1028
1029 arg.push_back(old_prefix_arg);
1030 arg.push_back(new_prefix_arg);
1031
1032 m_arguments.push_back(arg);
1033 }
1034
1036
1037protected:
1038 void DoExecute(Args &command, CommandReturnObject &result) override {
1039 Target *target = GetTarget();
1040 assert(target && "target guaranteed by eCommandRequiresTarget");
1041 const size_t argc = command.GetArgumentCount();
1042 if (argc & 1) {
1043 result.AppendError("add requires an even number of arguments\n");
1044 } else {
1045 for (size_t i = 0; i < argc; i += 2) {
1046 const char *from = command.GetArgumentAtIndex(i);
1047 const char *to = command.GetArgumentAtIndex(i + 1);
1048
1049 if (from[0] && to[0]) {
1051 "target modules search path adding ImageSearchPath "
1052 "pair: '%s' -> '%s'",
1053 from, to);
1054 bool last_pair = ((argc - i) == 2);
1056 from, to, last_pair); // Notify if this is the last pair
1058 } else {
1059 if (from[0])
1060 result.AppendError("<path-prefix> can't be empty\n");
1061 else
1062 result.AppendError("<new-path-prefix> can't be empty\n");
1063 }
1064 }
1065 }
1066 }
1067};
1068
1069#pragma mark CommandObjectTargetModulesSearchPathsClear
1070
1072public:
1074 : CommandObjectParsed(interpreter, "target modules search-paths clear",
1075 "Clear all current image search path substitution "
1076 "pairs from the current target.",
1077 "target modules search-paths clear",
1078 eCommandRequiresTarget) {}
1079
1081
1082protected:
1083 void DoExecute(Args &command, CommandReturnObject &result) override {
1084 Target *target = GetTarget();
1085 assert(target && "target guaranteed by eCommandRequiresTarget");
1086 bool notify = true;
1087 target->GetImageSearchPathList().Clear(notify);
1089 }
1090};
1091
1092#pragma mark CommandObjectTargetModulesSearchPathsInsert
1093
1095public:
1097 : CommandObjectParsed(interpreter, "target modules search-paths insert",
1098 "Insert a new image search path substitution pair "
1099 "into the current target at the specified index.",
1100 nullptr, eCommandRequiresTarget) {
1103 CommandArgumentData index_arg;
1104 CommandArgumentData old_prefix_arg;
1105 CommandArgumentData new_prefix_arg;
1106
1107 // Define the first and only variant of this arg.
1108 index_arg.arg_type = eArgTypeIndex;
1109 index_arg.arg_repetition = eArgRepeatPlain;
1110
1111 // Put the one and only variant into the first arg for m_arguments:
1112 arg1.push_back(index_arg);
1113
1114 // Define the first variant of this arg pair.
1115 old_prefix_arg.arg_type = eArgTypeOldPathPrefix;
1116 old_prefix_arg.arg_repetition = eArgRepeatPairPlus;
1117
1118 // Define the first variant of this arg pair.
1119 new_prefix_arg.arg_type = eArgTypeNewPathPrefix;
1120 new_prefix_arg.arg_repetition = eArgRepeatPairPlus;
1121
1122 // There are two required arguments that must always occur together, i.e.
1123 // an argument "pair". Because they must always occur together, they are
1124 // treated as two variants of one argument rather than two independent
1125 // arguments. Push them both into the same argument position for
1126 // m_arguments...
1127
1128 arg2.push_back(old_prefix_arg);
1129 arg2.push_back(new_prefix_arg);
1130
1131 // Add arguments to m_arguments.
1132 m_arguments.push_back(arg1);
1133 m_arguments.push_back(arg2);
1134 }
1135
1137
1138 void
1140 OptionElementVector &opt_element_vector) override {
1141 if (!m_exe_ctx.HasTargetScope() || request.GetCursorIndex() != 0)
1142 return;
1143
1144 Target *target = m_exe_ctx.GetTargetPtr();
1145
1146 const PathMappingList &list = target->GetImageSearchPathList();
1147 const size_t num = list.GetSize();
1148 std::string old_path, new_path;
1149 for (size_t i = 0; i < num; ++i) {
1150 if (!list.GetPathsAtIndex(i, old_path, new_path))
1151 break;
1152 StreamString strm;
1153 strm << old_path << " -> " << new_path;
1154 request.TryCompleteCurrentArg(std::to_string(i), strm.GetString());
1155 }
1156 }
1157
1158protected:
1159 void DoExecute(Args &command, CommandReturnObject &result) override {
1160 Target *target = GetTarget();
1161 assert(target && "target guaranteed by eCommandRequiresTarget");
1162 size_t argc = command.GetArgumentCount();
1163 // check for at least 3 arguments and an odd number of parameters
1164 if (argc >= 3 && argc & 1) {
1165 uint32_t insert_idx;
1166
1167 if (!llvm::to_integer(command.GetArgumentAtIndex(0), insert_idx)) {
1168 result.AppendErrorWithFormat(
1169 "<index> parameter is not an integer: '%s'",
1170 command.GetArgumentAtIndex(0));
1171 return;
1172 }
1173
1174 // shift off the index
1175 command.Shift();
1176 argc = command.GetArgumentCount();
1177
1178 for (uint32_t i = 0; i < argc; i += 2, ++insert_idx) {
1179 const char *from = command.GetArgumentAtIndex(i);
1180 const char *to = command.GetArgumentAtIndex(i + 1);
1181
1182 if (from[0] && to[0]) {
1183 bool last_pair = ((argc - i) == 2);
1184 target->GetImageSearchPathList().Insert(from, to, insert_idx,
1185 last_pair);
1187 } else {
1188 if (from[0])
1189 result.AppendError("<path-prefix> can't be empty\n");
1190 else
1191 result.AppendError("<new-path-prefix> can't be empty\n");
1192 return;
1193 }
1194 }
1195 } else {
1196 result.AppendError("insert requires at least three arguments\n");
1197 }
1198 }
1199};
1200
1201#pragma mark CommandObjectTargetModulesSearchPathsList
1202
1204public:
1206 : CommandObjectParsed(interpreter, "target modules search-paths list",
1207 "List all current image search path substitution "
1208 "pairs in the current target.",
1209 "target modules search-paths list",
1210 eCommandRequiresTarget) {}
1211
1213
1214protected:
1215 void DoExecute(Args &command, CommandReturnObject &result) override {
1216 Target *target = GetTarget();
1217 assert(target && "target guaranteed by eCommandRequiresTarget");
1218 target->GetImageSearchPathList().Dump(&result.GetOutputStream());
1220 }
1221};
1222
1223#pragma mark CommandObjectTargetModulesSearchPathsQuery
1224
1226public:
1229 interpreter, "target modules search-paths query",
1230 "Transform a path using the first applicable image search path.",
1231 nullptr, eCommandRequiresTarget) {
1233 }
1234
1236
1237protected:
1238 void DoExecute(Args &command, CommandReturnObject &result) override {
1239 Target *target = GetTarget();
1240 assert(target && "target guaranteed by eCommandRequiresTarget");
1241 if (command.GetArgumentCount() != 1) {
1242 result.AppendError("query requires one argument\n");
1243 return;
1244 }
1245
1246 llvm::StringRef orig(command.GetArgumentAtIndex(0));
1247 std::string transformed;
1248 if (target->GetImageSearchPathList().RemapPath(orig, transformed))
1249 result.GetOutputStream().Format("{0}\n", transformed);
1250 else
1251 result.GetOutputStream().Format("{0}\n", orig);
1252
1254 }
1255};
1256
1257// Static Helper functions
1258static void DumpModuleArchitecture(Stream &strm, Module *module,
1259 bool full_triple, uint32_t width) {
1260 if (module) {
1261 StreamString arch_strm;
1262
1263 if (full_triple)
1264 module->GetArchitecture().DumpTriple(arch_strm.AsRawOstream());
1265 else
1266 arch_strm.PutCString(module->GetArchitecture().GetArchitectureName());
1267 std::string arch_str = std::string(arch_strm.GetString());
1268
1269 if (width)
1270 strm.Printf("%-*s", width, arch_str.c_str());
1271 else
1272 strm.PutCString(arch_str);
1273 }
1274}
1275
1276static void DumpModuleUUID(Stream &strm, Module *module) {
1277 if (module && module->GetUUID().IsValid())
1278 module->GetUUID().Dump(strm);
1279 else
1280 strm.PutCString(" ");
1281}
1282
1284 Stream &strm, Module *module,
1285 const FileSpec &file_spec,
1286 lldb::DescriptionLevel desc_level) {
1287 uint32_t num_matches = 0;
1288 if (module) {
1289 SymbolContextList sc_list;
1290 num_matches = module->ResolveSymbolContextsForFileSpec(
1291 file_spec, 0, false, eSymbolContextCompUnit, sc_list);
1292
1293 bool first_module = true;
1294 for (const SymbolContext &sc : sc_list) {
1295 if (!first_module)
1296 strm << "\n\n";
1297
1298 strm << "Line table for " << sc.comp_unit->GetPrimaryFile() << " in `"
1299 << module->GetFileSpec().GetFilename() << "\n";
1300 LineTable *line_table = sc.comp_unit->GetLineTable();
1301 if (line_table)
1302 line_table->GetDescription(
1303 &strm, interpreter.GetExecutionContext().GetTargetPtr(),
1304 desc_level);
1305 else
1306 strm << "No line table";
1307
1308 first_module = false;
1309 }
1310 }
1311 return num_matches;
1312}
1313
1314static void DumpFullpath(Stream &strm, const FileSpec *file_spec_ptr,
1315 uint32_t width) {
1316 if (file_spec_ptr) {
1317 if (width > 0) {
1318 std::string fullpath = file_spec_ptr->GetPath();
1319 strm.Printf("%-*s", width, fullpath.c_str());
1320 return;
1321 } else {
1322 file_spec_ptr->Dump(strm.AsRawOstream());
1323 return;
1324 }
1325 }
1326 // Keep the width spacing correct if things go wrong...
1327 if (width > 0)
1328 strm.Printf("%-*s", width, "");
1329}
1330
1331static void DumpDirectory(Stream &strm, const FileSpec *file_spec_ptr,
1332 uint32_t width) {
1333 if (file_spec_ptr) {
1334 if (width > 0)
1335 strm.Format("{0}", fmt_align(file_spec_ptr->GetDirectory(),
1336 llvm::AlignStyle::Left, width));
1337 else
1338 strm.PutCString(file_spec_ptr->GetDirectory());
1339 return;
1340 }
1341 // Keep the width spacing correct if things go wrong...
1342 if (width > 0)
1343 strm.Printf("%-*s", width, "");
1344}
1345
1346static void DumpBasename(Stream &strm, const FileSpec *file_spec_ptr,
1347 uint32_t width) {
1348 if (file_spec_ptr) {
1349 if (width > 0)
1350 strm.Format("{0}", fmt_align(file_spec_ptr->GetFilename(),
1351 llvm::AlignStyle::Left, width));
1352 else
1353 strm.PutCString(file_spec_ptr->GetFilename());
1354 return;
1355 }
1356 // Keep the width spacing correct if things go wrong...
1357 if (width > 0)
1358 strm.Printf("%-*s", width, "");
1359}
1360
1361static size_t DumpModuleObjfileHeaders(Stream &strm, ModuleList &module_list) {
1362 std::lock_guard<std::recursive_mutex> guard(module_list.GetMutex());
1363 const size_t num_modules = module_list.GetSize();
1364 if (num_modules == 0)
1365 return 0;
1366
1367 size_t num_dumped = 0;
1368 strm.Format("Dumping headers for {0} module(s).\n", num_modules);
1369 strm.IndentMore();
1370 for (ModuleSP module_sp : module_list.ModulesNoLocking()) {
1371 if (module_sp) {
1372 if (num_dumped++ > 0) {
1373 strm.EOL();
1374 strm.EOL();
1375 }
1376 ObjectFile *objfile = module_sp->GetObjectFile();
1377 if (objfile)
1378 objfile->Dump(&strm);
1379 else {
1380 strm.Format("No object file for module: {0:F}\n",
1381 module_sp->GetFileSpec());
1382 }
1383 }
1384 }
1385 strm.IndentLess();
1386 return num_dumped;
1387}
1388
1389static void DumpModuleSymtab(CommandInterpreter &interpreter, Stream &strm,
1390 Module *module, SortOrder sort_order,
1391 Mangled::NamePreference name_preference) {
1392 if (!module)
1393 return;
1394 if (Symtab *symtab = module->GetSymtab())
1395 symtab->Dump(&strm, interpreter.GetExecutionContext().GetTargetPtr(),
1396 sort_order, name_preference);
1397}
1398
1399static void DumpModuleSections(CommandInterpreter &interpreter, Stream &strm,
1400 Module *module) {
1401 if (module) {
1402 SectionList *section_list = module->GetSectionList();
1403 if (section_list) {
1404 strm.Printf("Sections for '%s' (%s):\n",
1405 module->GetSpecificationDescription().c_str(),
1407 section_list->Dump(strm.AsRawOstream(), strm.GetIndentLevel() + 2,
1408 interpreter.GetExecutionContext().GetTargetPtr(), true,
1409 UINT32_MAX);
1410 }
1411 }
1412}
1413
1414static bool DumpModuleSymbolFile(Stream &strm, Module *module) {
1415 if (module) {
1416 if (SymbolFile *symbol_file = module->GetSymbolFile(true)) {
1417 symbol_file->Dump(strm);
1418 return true;
1419 }
1420 }
1421 return false;
1422}
1423
1425 Module *module, bool errors_only,
1426 bool load_all_debug_info) {
1427 if (module) {
1428 if (SymbolFile *symbol_file = module->GetSymbolFile(/*can_create=*/true)) {
1430 if (symbol_file->GetSeparateDebugInfo(d, errors_only,
1431 load_all_debug_info)) {
1432 list.AddItem(
1433 std::make_shared<StructuredData::Dictionary>(std::move(d)));
1434 return true;
1435 }
1436 }
1437 }
1438 return false;
1439}
1440
1441static void DumpDwoFilesTable(Stream &strm,
1442 StructuredData::Array &dwo_listings) {
1443 strm.PutCString("Dwo ID Err Dwo Path");
1444 strm.EOL();
1445 strm.PutCString(
1446 "------------------ --- -----------------------------------------");
1447 strm.EOL();
1448 dwo_listings.ForEach([&strm](StructuredData::Object *dwo) {
1450 if (!dict)
1451 return false;
1452
1453 uint64_t dwo_id;
1454 if (dict->GetValueForKeyAsInteger("dwo_id", dwo_id))
1455 strm.Printf("0x%16.16" PRIx64 " ", dwo_id);
1456 else
1457 strm.PutCString("0x???????????????? ");
1458
1459 llvm::StringRef error;
1460 if (dict->GetValueForKeyAsString("error", error))
1461 strm << "E " << error;
1462 else {
1463 llvm::StringRef resolved_dwo_path;
1464 if (dict->GetValueForKeyAsString("resolved_dwo_path",
1465 resolved_dwo_path)) {
1466 strm << " " << resolved_dwo_path;
1467 if (resolved_dwo_path.ends_with(".dwp")) {
1468 llvm::StringRef dwo_name;
1469 if (dict->GetValueForKeyAsString("dwo_name", dwo_name))
1470 strm << "(" << dwo_name << ")";
1471 }
1472 }
1473 }
1474 strm.EOL();
1475 return true;
1476 });
1477}
1478
1479static void DumpOsoFilesTable(Stream &strm,
1480 StructuredData::Array &oso_listings) {
1481 strm.PutCString("Mod Time Err Oso Path");
1482 strm.EOL();
1483 strm.PutCString("------------------ --- ---------------------");
1484 strm.EOL();
1485 oso_listings.ForEach([&strm](StructuredData::Object *oso) {
1487 if (!dict)
1488 return false;
1489
1490 uint32_t oso_mod_time;
1491 if (dict->GetValueForKeyAsInteger("oso_mod_time", oso_mod_time))
1492 strm.Printf("0x%16.16" PRIx32 " ", oso_mod_time);
1493
1494 llvm::StringRef error;
1495 if (dict->GetValueForKeyAsString("error", error))
1496 strm << "E " << error;
1497 else {
1498 llvm::StringRef oso_path;
1499 if (dict->GetValueForKeyAsString("oso_path", oso_path))
1500 strm << " " << oso_path;
1501 }
1502 strm.EOL();
1503 return true;
1504 });
1505}
1506
1507static void
1508DumpAddress(ExecutionContextScope *exe_scope, const Address &so_addr,
1509 bool verbose, bool all_ranges, Stream &strm,
1510 std::optional<Stream::HighlightSettings> settings = std::nullopt) {
1511 strm.IndentMore();
1512 strm.Indent(" Address: ");
1513 so_addr.Dump(&strm, exe_scope, Address::DumpStyleModuleWithFileAddress);
1514 strm.PutCString(" (");
1515 so_addr.Dump(&strm, exe_scope, Address::DumpStyleSectionNameOffset);
1516 strm.PutCString(")\n");
1517 strm.Indent(" Summary: ");
1518 const uint32_t save_indent = strm.GetIndentLevel();
1519 strm.SetIndentLevel(save_indent + 13);
1520 so_addr.Dump(&strm, exe_scope, Address::DumpStyleResolvedDescription,
1521 Address::DumpStyleInvalid, UINT32_MAX, false, settings);
1522 strm.SetIndentLevel(save_indent);
1523 // Print out detailed address information when verbose is enabled
1524 if (verbose) {
1525 strm.EOL();
1526 so_addr.Dump(&strm, exe_scope, Address::DumpStyleDetailedSymbolContext,
1527 Address::DumpStyleInvalid, UINT32_MAX, all_ranges, settings);
1528 }
1529 strm.IndentLess();
1530}
1531
1532static bool LookupAddressInModule(CommandInterpreter &interpreter, Stream &strm,
1533 Module *module, uint32_t resolve_mask,
1534 lldb::addr_t raw_addr, lldb::addr_t offset,
1535 bool verbose, bool all_ranges) {
1536 if (module) {
1537 lldb::addr_t addr = raw_addr - offset;
1538 Address so_addr;
1539 SymbolContext sc;
1540 Target *target = interpreter.GetExecutionContext().GetTargetPtr();
1541 if (target && target->HasLoadedSections()) {
1542 if (!target->ResolveLoadAddress(addr, so_addr))
1543 return false;
1544 else if (so_addr.GetModule().get() != module)
1545 return false;
1546 } else {
1547 if (!module->ResolveFileAddress(addr, so_addr))
1548 return false;
1549 }
1550
1551 ExecutionContextScope *exe_scope =
1553 DumpAddress(exe_scope, so_addr, verbose, all_ranges, strm);
1554 return true;
1555 }
1556
1557 return false;
1558}
1559
1560static uint32_t LookupSymbolInModule(CommandInterpreter &interpreter,
1561 Stream &strm, Module *module,
1562 const char *name, bool name_is_regex,
1563 bool verbose, bool all_ranges) {
1564 if (!module)
1565 return 0;
1566
1567 Symtab *symtab = module->GetSymtab();
1568 if (!symtab)
1569 return 0;
1570
1571 SymbolContext sc;
1572 const bool use_color = interpreter.GetDebugger().GetUseColor();
1573 std::vector<uint32_t> match_indexes;
1574 ConstString symbol_name(name);
1575 uint32_t num_matches = 0;
1576 if (name_is_regex) {
1577 RegularExpression name_regexp(symbol_name.GetStringRef());
1578 num_matches = symtab->AppendSymbolIndexesMatchingRegExAndType(
1579 name_regexp, eSymbolTypeAny, match_indexes);
1580 } else {
1581 num_matches =
1582 symtab->AppendSymbolIndexesWithName(symbol_name, match_indexes);
1583 }
1584
1585 if (num_matches > 0) {
1586 strm.Indent();
1587 strm.Printf("%u symbols match %s'%s' in ", num_matches,
1588 name_is_regex ? "the regular expression " : "", name);
1589 DumpFullpath(strm, &module->GetFileSpec(), 0);
1590 strm.PutCString(":\n");
1591 strm.IndentMore();
1593 name, interpreter.GetDebugger().GetRegexMatchAnsiPrefix(),
1594 interpreter.GetDebugger().GetRegexMatchAnsiSuffix());
1595 for (uint32_t i = 0; i < num_matches; ++i) {
1596 const Symbol *symbol = symtab->SymbolAtIndex(match_indexes[i]);
1597 if (symbol) {
1598 if (symbol->ValueIsAddress()) {
1601 symbol->GetAddressRef(), verbose, all_ranges, strm,
1602 use_color && name_is_regex
1603 ? std::optional<Stream::HighlightSettings>{settings}
1604 : std::nullopt);
1605 strm.EOL();
1606 } else {
1607 strm.IndentMore();
1608 strm.Indent(" Name: ");
1610 symbol->GetDisplayName().GetStringRef(),
1611 use_color && name_is_regex
1612 ? std::optional<Stream::HighlightSettings>{settings}
1613 : std::nullopt);
1614 strm.EOL();
1615 strm.Indent(" Value: ");
1616 strm.Printf("0x%16.16" PRIx64 "\n", symbol->GetRawValue());
1617 if (symbol->GetByteSizeIsValid()) {
1618 strm.Indent(" Size: ");
1619 strm.Printf("0x%16.16" PRIx64 "\n", symbol->GetByteSize());
1620 }
1621 strm.IndentLess();
1622 }
1623 }
1624 }
1625 strm.IndentLess();
1626 }
1627 return num_matches;
1628}
1629
1631 ExecutionContextScope *exe_scope, Stream &strm,
1632 const SymbolContextList &sc_list, bool verbose, bool all_ranges,
1633 std::optional<Stream::HighlightSettings> settings = std::nullopt) {
1634 strm.IndentMore();
1635 bool first_module = true;
1636 for (const SymbolContext &sc : sc_list) {
1637 if (!first_module)
1638 strm.EOL();
1639
1640 Address addr;
1641 if (sc.line_entry.IsValid())
1642 addr = sc.line_entry.range.GetBaseAddress();
1643 else if (sc.block && sc.block->GetContainingInlinedBlock())
1644 sc.block->GetContainingInlinedBlock()->GetStartAddress(addr);
1645 else
1646 addr = sc.GetFunctionOrSymbolAddress();
1647
1648 DumpAddress(exe_scope, addr, verbose, all_ranges, strm, settings);
1649 first_module = false;
1650 }
1651 strm.IndentLess();
1652}
1653
1655 Stream &strm, Module *module,
1656 const char *name, bool name_is_regex,
1657 const ModuleFunctionSearchOptions &options,
1658 bool verbose, bool all_ranges) {
1659 if (module && name && name[0]) {
1660 SymbolContextList sc_list;
1661 size_t num_matches = 0;
1662 if (name_is_regex) {
1663 RegularExpression function_name_regex((llvm::StringRef(name)));
1664 module->FindFunctions(function_name_regex, options, sc_list);
1665 } else {
1666 ConstString function_name(name);
1667 module->FindFunctions(function_name, CompilerDeclContext(),
1668 eFunctionNameTypeAuto, options, sc_list);
1669 }
1670 num_matches = sc_list.GetSize();
1671 if (num_matches) {
1672 strm.Indent();
1673 strm.Printf("%" PRIu64 " match%s found in ", (uint64_t)num_matches,
1674 num_matches > 1 ? "es" : "");
1675 DumpFullpath(strm, &module->GetFileSpec(), 0);
1676 strm.PutCString(":\n");
1679 strm, sc_list, verbose, all_ranges);
1680 }
1681 return num_matches;
1682 }
1683 return 0;
1684}
1685
1686static size_t LookupTypeInModule(Target *target,
1687 CommandInterpreter &interpreter, Stream &strm,
1688 Module *module, const char *name_cstr,
1689 bool name_is_regex) {
1690 if (module && name_cstr && name_cstr[0]) {
1691 TypeQuery query(name_cstr);
1692 TypeResults results;
1693 module->FindTypes(query, results);
1694
1695 TypeList type_list;
1696 SymbolContext sc;
1697 if (module)
1698 sc.module_sp = module->shared_from_this();
1699 // Sort the type results and put the results that matched in \a module
1700 // first if \a module was specified.
1701 sc.SortTypeList(results.GetTypeMap(), type_list);
1702 if (type_list.Empty())
1703 return 0;
1704
1705 const uint64_t num_matches = type_list.GetSize();
1706
1707 strm.Indent();
1708 strm.Printf("%" PRIu64 " match%s found in ", num_matches,
1709 num_matches > 1 ? "es" : "");
1710 DumpFullpath(strm, &module->GetFileSpec(), 0);
1711 strm.PutCString(":\n");
1712 for (TypeSP type_sp : type_list.Types()) {
1713 if (!type_sp)
1714 continue;
1715 // Resolve the clang type so that any forward references to types
1716 // that haven't yet been parsed will get parsed.
1717 type_sp->GetFullCompilerType();
1718 type_sp->GetDescription(&strm, eDescriptionLevelFull, true, target);
1719 // Print all typedef chains
1720 TypeSP typedef_type_sp(type_sp);
1721 TypeSP typedefed_type_sp(typedef_type_sp->GetTypedefType());
1722 while (typedefed_type_sp) {
1723 strm.EOL();
1724 strm.Printf(" typedef '%s': ",
1725 typedef_type_sp->GetName().GetCString());
1726 typedefed_type_sp->GetFullCompilerType();
1727 typedefed_type_sp->GetDescription(&strm, eDescriptionLevelFull, true,
1728 target);
1729 typedef_type_sp = typedefed_type_sp;
1730 typedefed_type_sp = typedef_type_sp->GetTypedefType();
1731 }
1732 strm.EOL();
1733 }
1734 return type_list.GetSize();
1735 }
1736 return 0;
1737}
1738
1739static size_t LookupTypeHere(Target *target, CommandInterpreter &interpreter,
1740 Stream &strm, Module &module,
1741 const char *name_cstr, bool name_is_regex) {
1742 TypeQuery query(name_cstr);
1743 TypeResults results;
1744 module.FindTypes(query, results);
1745 TypeList type_list;
1746 SymbolContext sc;
1747 sc.module_sp = module.shared_from_this();
1748 sc.SortTypeList(results.GetTypeMap(), type_list);
1749 if (type_list.Empty())
1750 return 0;
1751
1752 strm.Indent();
1753 strm.PutCString("Best match found in ");
1754 DumpFullpath(strm, &module.GetFileSpec(), 0);
1755 strm.PutCString(":\n");
1756
1757 TypeSP type_sp(type_list.GetTypeAtIndex(0));
1758 if (type_sp) {
1759 // Resolve the clang type so that any forward references to types that
1760 // haven't yet been parsed will get parsed.
1761 type_sp->GetFullCompilerType();
1762 type_sp->GetDescription(&strm, eDescriptionLevelFull, true, target);
1763 // Print all typedef chains.
1764 TypeSP typedef_type_sp(type_sp);
1765 TypeSP typedefed_type_sp(typedef_type_sp->GetTypedefType());
1766 while (typedefed_type_sp) {
1767 strm.EOL();
1768 strm.Printf(" typedef '%s': ",
1769 typedef_type_sp->GetName().GetCString());
1770 typedefed_type_sp->GetFullCompilerType();
1771 typedefed_type_sp->GetDescription(&strm, eDescriptionLevelFull, true,
1772 target);
1773 typedef_type_sp = typedefed_type_sp;
1774 typedefed_type_sp = typedef_type_sp->GetTypedefType();
1775 }
1776 }
1777 strm.EOL();
1778 return type_list.GetSize();
1779}
1780
1782 Stream &strm, Module *module,
1783 const FileSpec &file_spec,
1784 uint32_t line, bool check_inlines,
1785 bool verbose, bool all_ranges) {
1786 if (module && file_spec) {
1787 SymbolContextList sc_list;
1788 const uint32_t num_matches = module->ResolveSymbolContextsForFileSpec(
1789 file_spec, line, check_inlines, eSymbolContextEverything, sc_list);
1790 if (num_matches > 0) {
1791 strm.Indent();
1792 strm.Printf("%u match%s found in ", num_matches,
1793 num_matches > 1 ? "es" : "");
1794 strm << file_spec;
1795 if (line > 0)
1796 strm.Printf(":%u", line);
1797 strm << " in ";
1798 DumpFullpath(strm, &module->GetFileSpec(), 0);
1799 strm.PutCString(":\n");
1802 strm, sc_list, verbose, all_ranges);
1803 return num_matches;
1804 }
1805 }
1806 return 0;
1807}
1808
1809static size_t FindModulesByName(Target *target, const char *module_name,
1810 ModuleList &module_list,
1811 bool check_global_list) {
1812 FileSpec module_file_spec(module_name);
1813 ModuleSpec module_spec(module_file_spec);
1814
1815 const size_t initial_size = module_list.GetSize();
1816
1817 if (check_global_list) {
1818 // Check the global list
1819 std::lock_guard<std::recursive_mutex> guard(
1821 const size_t num_modules = Module::GetNumberAllocatedModules();
1822 ModuleSP module_sp;
1823 for (size_t image_idx = 0; image_idx < num_modules; ++image_idx) {
1824 Module *module = Module::GetAllocatedModuleAtIndex(image_idx);
1825
1826 if (module) {
1827 if (module->MatchesModuleSpec(module_spec)) {
1828 module_sp = module->shared_from_this();
1829 module_list.AppendIfNeeded(module_sp);
1830 }
1831 }
1832 }
1833 } else {
1834 if (target) {
1835 target->GetImages().FindModules(module_spec, module_list);
1836 const size_t num_matches = module_list.GetSize();
1837
1838 // Not found in our module list for our target, check the main shared
1839 // module list in case it is a extra file used somewhere else
1840 if (num_matches == 0) {
1841 module_spec.GetArchitecture() = target->GetArchitecture();
1842 ModuleList::FindSharedModules(module_spec, module_list);
1843 }
1844 } else {
1845 ModuleList::FindSharedModules(module_spec, module_list);
1846 }
1847 }
1848
1849 return module_list.GetSize() - initial_size;
1850}
1851
1852#pragma mark CommandObjectTargetModulesModuleAutoComplete
1853
1854// A base command object class that can auto complete with module file
1855// paths
1856
1858 : public CommandObjectParsed {
1859public:
1861 const char *name,
1862 const char *help,
1863 const char *syntax,
1864 uint32_t flags = 0)
1865 : CommandObjectParsed(interpreter, name, help, syntax, flags) {
1867 }
1868
1870
1871 void
1877};
1878
1879#pragma mark CommandObjectTargetModulesSourceFileAutoComplete
1880
1881// A base command object class that can auto complete with module source
1882// file paths
1883
1885 : public CommandObjectParsed {
1886public:
1888 CommandInterpreter &interpreter, const char *name, const char *help,
1889 const char *syntax, uint32_t flags)
1890 : CommandObjectParsed(interpreter, name, help, syntax, flags) {
1892 }
1893
1895
1896 void
1902};
1903
1904#pragma mark CommandObjectTargetModulesDumpObjfile
1905
1908public:
1911 interpreter, "target modules dump objfile",
1912 "Dump the object file headers from one or more target modules.",
1913 nullptr, eCommandRequiresTarget) {}
1914
1916
1917protected:
1918 void DoExecute(Args &command, CommandReturnObject &result) override {
1919 Target *target = GetTarget();
1920 assert(target && "target guaranteed by eCommandRequiresTarget");
1921 size_t num_dumped = 0;
1922 if (command.GetArgumentCount() == 0) {
1923 // Dump all headers for all modules images
1924 num_dumped = DumpModuleObjfileHeaders(result.GetOutputStream(),
1925 target->GetImages());
1926 if (num_dumped == 0) {
1927 result.AppendError("the target has no associated executable images");
1928 }
1929 } else {
1930 // Find the modules that match the basename or full path.
1931 ModuleList module_list;
1932 const char *arg_cstr;
1933 for (int arg_idx = 0;
1934 (arg_cstr = command.GetArgumentAtIndex(arg_idx)) != nullptr;
1935 ++arg_idx) {
1936 size_t num_matched =
1937 FindModulesByName(target, arg_cstr, module_list, true);
1938 if (num_matched == 0) {
1940 "unable to find an image that matches '{0}'", arg_cstr);
1941 }
1942 }
1943 // Dump all the modules we found.
1944 num_dumped =
1945 DumpModuleObjfileHeaders(result.GetOutputStream(), module_list);
1946 }
1947
1948 if (num_dumped > 0) {
1950 } else {
1951 result.AppendError("no matching executable images found");
1952 }
1953 }
1954};
1955
1956#define LLDB_OPTIONS_target_modules_dump_symtab
1957#include "CommandOptions.inc"
1958
1961public:
1964 interpreter, "target modules dump symtab",
1965 "Dump the symbol table from one or more target modules.", nullptr,
1966 eCommandRequiresTarget) {}
1967
1969
1970 Options *GetOptions() override { return &m_options; }
1971
1972 class CommandOptions : public Options {
1973 public:
1974 CommandOptions() = default;
1975
1976 ~CommandOptions() override = default;
1977
1978 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1979 ExecutionContext *execution_context) override {
1980 Status error;
1981 const int short_option = m_getopt_table[option_idx].val;
1982
1983 switch (short_option) {
1984 case 'm':
1985 m_prefer_mangled.SetCurrentValue(true);
1986 m_prefer_mangled.SetOptionWasSet();
1987 break;
1988
1989 case 's':
1991 option_arg, GetDefinitions()[option_idx].enum_values,
1993 break;
1994
1995 default:
1996 llvm_unreachable("Unimplemented option");
1997 }
1998 return error;
1999 }
2000
2001 void OptionParsingStarting(ExecutionContext *execution_context) override {
2003 m_prefer_mangled.Clear();
2004 }
2005
2006 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
2007 return llvm::ArrayRef(g_target_modules_dump_symtab_options);
2008 }
2009
2012 };
2013
2014protected:
2015 void DoExecute(Args &command, CommandReturnObject &result) override {
2016 Target *target = GetTarget();
2017 assert(target && "target guaranteed by eCommandRequiresTarget");
2018 uint32_t num_dumped = 0;
2019 Mangled::NamePreference name_preference =
2020 (m_options.m_prefer_mangled ? Mangled::ePreferMangled
2022
2023 if (command.GetArgumentCount() == 0) {
2024 // Dump all sections for all modules images
2025 const ModuleList &module_list = target->GetImages();
2026 std::lock_guard<std::recursive_mutex> guard(module_list.GetMutex());
2027 const size_t num_modules = module_list.GetSize();
2028 if (num_modules > 0) {
2029 result.GetOutputStream().Format(
2030 "Dumping symbol table for {0} modules.\n", num_modules);
2031 for (ModuleSP module_sp : module_list.ModulesNoLocking()) {
2032 if (num_dumped > 0) {
2033 result.GetOutputStream().EOL();
2034 result.GetOutputStream().EOL();
2035 }
2037 "Interrupted in dump all symtabs with {0} "
2038 "of {1} dumped.", num_dumped, num_modules))
2039 break;
2040
2041 num_dumped++;
2043 module_sp.get(), m_options.m_sort_order,
2044 name_preference);
2045 }
2046 } else {
2047 result.AppendError("the target has no associated executable images");
2048 return;
2049 }
2050 } else {
2051 // Dump specified images (by basename or fullpath)
2052 const char *arg_cstr;
2053 for (int arg_idx = 0;
2054 (arg_cstr = command.GetArgumentAtIndex(arg_idx)) != nullptr;
2055 ++arg_idx) {
2056 ModuleList module_list;
2057 const size_t num_matches =
2058 FindModulesByName(target, arg_cstr, module_list, true);
2059 if (num_matches > 0) {
2060 for (ModuleSP module_sp : module_list.Modules()) {
2061 if (module_sp) {
2062 if (num_dumped > 0) {
2063 result.GetOutputStream().EOL();
2064 result.GetOutputStream().EOL();
2065 }
2067 "Interrupted in dump symtab list with {0} of {1} dumped.",
2068 num_dumped, num_matches))
2069 break;
2070
2071 num_dumped++;
2073 module_sp.get(), m_options.m_sort_order,
2074 name_preference);
2075 }
2076 }
2077 } else
2079 "unable to find an image that matches '{0}'", arg_cstr);
2080 }
2081 }
2082
2083 if (num_dumped > 0)
2085 else {
2086 result.AppendError("no matching executable images found");
2087 }
2088 }
2089
2091};
2092
2093#pragma mark CommandObjectTargetModulesDumpSections
2094
2095// Image section dumping command
2096
2099public:
2102 interpreter, "target modules dump sections",
2103 "Dump the sections from one or more target modules.",
2104 //"target modules dump sections [<file1> ...]")
2105 nullptr, eCommandRequiresTarget) {}
2106
2108
2109protected:
2110 void DoExecute(Args &command, CommandReturnObject &result) override {
2111 Target *target = GetTarget();
2112 assert(target && "target guaranteed by eCommandRequiresTarget");
2113 uint32_t num_dumped = 0;
2114
2115 if (command.GetArgumentCount() == 0) {
2116 // Dump all sections for all modules images
2117 const size_t num_modules = target->GetImages().GetSize();
2118 if (num_modules == 0) {
2119 result.AppendError("the target has no associated executable images");
2120 return;
2121 }
2122
2123 result.GetOutputStream().Format("Dumping sections for {0} modules.\n",
2124 num_modules);
2125 for (size_t image_idx = 0; image_idx < num_modules; ++image_idx) {
2127 "Interrupted in dump all sections with {0} of {1} dumped",
2128 image_idx, num_modules))
2129 break;
2130
2131 num_dumped++;
2134 target->GetImages().GetModulePointerAtIndex(image_idx));
2135 }
2136 } else {
2137 // Dump specified images (by basename or fullpath)
2138 const char *arg_cstr;
2139 for (int arg_idx = 0;
2140 (arg_cstr = command.GetArgumentAtIndex(arg_idx)) != nullptr;
2141 ++arg_idx) {
2142 ModuleList module_list;
2143 const size_t num_matches =
2144 FindModulesByName(target, arg_cstr, module_list, true);
2145 if (num_matches > 0) {
2146 for (size_t i = 0; i < num_matches; ++i) {
2148 "Interrupted in dump section list with {0} of {1} dumped.",
2149 i, num_matches))
2150 break;
2151
2152 Module *module = module_list.GetModulePointerAtIndex(i);
2153 if (module) {
2154 num_dumped++;
2156 module);
2157 }
2158 }
2159 } else {
2160 // Check the global list
2161 std::lock_guard<std::recursive_mutex> guard(
2163
2165 "unable to find an image that matches '{0}'", arg_cstr);
2166 }
2167 }
2168 }
2169
2170 if (num_dumped > 0)
2172 else {
2173 result.AppendError("no matching executable images found");
2174 }
2175 }
2176};
2177
2178#pragma mark CommandObjectTargetModulesDumpClangAST
2179
2180// Clang AST dumping command
2181
2184public:
2187 interpreter, "target modules dump ast",
2188 "Dump the clang ast for a given module's symbol file.",
2189 "target modules dump ast [--filter <name>] [<file1> ...]",
2190 eCommandRequiresTarget),
2191 m_filter(LLDB_OPT_SET_1, false, "filter", 'f', 0, eArgTypeName,
2192 "Dump only the decls whose names contain the specified filter "
2193 "string.",
2194 /*default_value=*/"") {
2196 m_option_group.Finalize();
2197 }
2198
2199 Options *GetOptions() override { return &m_option_group; }
2200
2202
2205
2206protected:
2207 void DoExecute(Args &command, CommandReturnObject &result) override {
2208 Target *target = GetTarget();
2209 assert(target && "target guaranteed by eCommandRequiresTarget");
2210 const ModuleList &module_list = target->GetImages();
2211 const size_t num_modules = module_list.GetSize();
2212 if (num_modules == 0) {
2213 result.AppendError("the target has no associated executable images");
2214 return;
2215 }
2216
2217 llvm::StringRef filter = m_filter.GetOptionValue().GetCurrentValueAsRef();
2218
2219 if (command.GetArgumentCount() == 0) {
2220 // Dump all ASTs for all modules images
2221 result.GetOutputStream().Format("Dumping clang ast for {0} modules.\n",
2222 num_modules);
2223 for (ModuleSP module_sp : module_list.ModulesNoLocking()) {
2224 if (INTERRUPT_REQUESTED(GetDebugger(), "Interrupted dumping clang ast"))
2225 break;
2226 if (SymbolFile *sf = module_sp->GetSymbolFile())
2227 sf->DumpClangAST(result.GetOutputStream(), filter,
2228 GetCommandInterpreter().GetDebugger().GetUseColor());
2229 }
2231 return;
2232 }
2233
2234 // Dump specified ASTs (by basename or fullpath)
2235 for (const Args::ArgEntry &arg : command.entries()) {
2236 ModuleList module_list;
2237 const size_t num_matches =
2238 FindModulesByName(target, arg.c_str(), module_list, true);
2239 if (num_matches == 0) {
2240 // Check the global list
2241 std::lock_guard<std::recursive_mutex> guard(
2243
2245 "unable to find an image that matches '{0}'", arg.c_str());
2246 continue;
2247 }
2248
2249 for (size_t i = 0; i < num_matches; ++i) {
2251 "Interrupted in dump clang ast list with {0} of {1} dumped.",
2252 i, num_matches))
2253 break;
2254
2255 Module *m = module_list.GetModulePointerAtIndex(i);
2256 if (SymbolFile *sf = m->GetSymbolFile())
2257 sf->DumpClangAST(result.GetOutputStream(), filter,
2258 GetCommandInterpreter().GetDebugger().GetUseColor());
2259 }
2260 }
2262 }
2263};
2264
2265#pragma mark CommandObjectTargetModulesDumpSymfile
2266
2267// Image debug symbol dumping command
2268
2271public:
2274 interpreter, "target modules dump symfile",
2275 "Dump the debug symbol file for one or more target modules.",
2276 //"target modules dump symfile [<file1> ...]")
2277 nullptr, eCommandRequiresTarget) {}
2278
2280
2281protected:
2282 void DoExecute(Args &command, CommandReturnObject &result) override {
2283 Target *target = GetTarget();
2284 assert(target && "target guaranteed by eCommandRequiresTarget");
2285 uint32_t num_dumped = 0;
2286
2287 if (command.GetArgumentCount() == 0) {
2288 // Dump all sections for all modules images
2289 const ModuleList &target_modules = target->GetImages();
2290 std::lock_guard<std::recursive_mutex> guard(target_modules.GetMutex());
2291 const size_t num_modules = target_modules.GetSize();
2292 if (num_modules == 0) {
2293 result.AppendError("the target has no associated executable images");
2294 return;
2295 }
2296 result.GetOutputStream().Format(
2297 "Dumping debug symbols for {0} modules.\n", num_modules);
2298 for (ModuleSP module_sp : target_modules.ModulesNoLocking()) {
2299 if (INTERRUPT_REQUESTED(GetDebugger(), "Interrupted in dumping all "
2300 "debug symbols with {0} of {1} modules dumped",
2301 num_dumped, num_modules))
2302 break;
2303
2304 if (DumpModuleSymbolFile(result.GetOutputStream(), module_sp.get()))
2305 num_dumped++;
2306 }
2307 } else {
2308 // Dump specified images (by basename or fullpath)
2309 const char *arg_cstr;
2310 for (int arg_idx = 0;
2311 (arg_cstr = command.GetArgumentAtIndex(arg_idx)) != nullptr;
2312 ++arg_idx) {
2313 ModuleList module_list;
2314 const size_t num_matches =
2315 FindModulesByName(target, arg_cstr, module_list, true);
2316 if (num_matches > 0) {
2317 for (size_t i = 0; i < num_matches; ++i) {
2318 if (INTERRUPT_REQUESTED(GetDebugger(), "Interrupted dumping {0} "
2319 "of {1} requested modules",
2320 i, num_matches))
2321 break;
2322 Module *module = module_list.GetModulePointerAtIndex(i);
2323 if (module) {
2324 if (DumpModuleSymbolFile(result.GetOutputStream(), module))
2325 num_dumped++;
2326 }
2327 }
2328 } else
2330 "unable to find an image that matches '{0}'", arg_cstr);
2331 }
2332 }
2333
2334 if (num_dumped > 0)
2336 else {
2337 result.AppendError("no matching executable images found");
2338 }
2339 }
2340};
2341
2342#pragma mark CommandObjectTargetModulesDumpLineTable
2343#define LLDB_OPTIONS_target_modules_dump
2344#include "CommandOptions.inc"
2345
2346// Image debug line table dumping command
2347
2350public:
2353 interpreter, "target modules dump line-table",
2354 "Dump the line table for one or more compilation units.", nullptr,
2355 eCommandRequiresTarget) {}
2356
2358
2359 Options *GetOptions() override { return &m_options; }
2360
2361protected:
2362 void DoExecute(Args &command, CommandReturnObject &result) override {
2363 Target *target = m_exe_ctx.GetTargetPtr();
2364 uint32_t total_num_dumped = 0;
2365
2366 if (command.GetArgumentCount() == 0) {
2367 result.AppendError("file option must be specified");
2368 return;
2369 } else {
2370 // Dump specified images (by basename or fullpath)
2371 const char *arg_cstr;
2372 for (int arg_idx = 0;
2373 (arg_cstr = command.GetArgumentAtIndex(arg_idx)) != nullptr;
2374 ++arg_idx) {
2375 FileSpec file_spec(arg_cstr);
2376
2377 const ModuleList &target_modules = target->GetImages();
2378 std::lock_guard<std::recursive_mutex> guard(target_modules.GetMutex());
2379 size_t num_modules = target_modules.GetSize();
2380 if (num_modules > 0) {
2381 uint32_t num_dumped = 0;
2382 for (ModuleSP module_sp : target_modules.ModulesNoLocking()) {
2384 "Interrupted in dump all line tables with "
2385 "{0} of {1} dumped", num_dumped,
2386 num_modules))
2387 break;
2388
2390 m_interpreter, result.GetOutputStream(), module_sp.get(),
2391 file_spec,
2394 num_dumped++;
2395 }
2396 if (num_dumped == 0)
2397 result.AppendWarningWithFormatv("no source filenames matched '{0}'",
2398 arg_cstr);
2399 else
2400 total_num_dumped += num_dumped;
2401 }
2402 }
2403 }
2404
2405 if (total_num_dumped > 0)
2407 else {
2408 result.AppendError("no source filenames matched any command arguments");
2409 }
2410 }
2411
2412 class CommandOptions : public Options {
2413 public:
2415
2416 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
2417 ExecutionContext *execution_context) override {
2418 assert(option_idx == 0 && "We only have one option.");
2419 m_verbose = true;
2420
2421 return Status();
2422 }
2423
2424 void OptionParsingStarting(ExecutionContext *execution_context) override {
2425 m_verbose = false;
2426 }
2427
2428 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
2429 return llvm::ArrayRef(g_target_modules_dump_options);
2430 }
2431
2433 };
2434
2436};
2437
2438#pragma mark CommandObjectTargetModulesDumpSeparateDebugInfoFiles
2439#define LLDB_OPTIONS_target_modules_dump_separate_debug_info
2440#include "CommandOptions.inc"
2441
2442// Image debug separate debug info dumping command
2443
2446public:
2448 CommandInterpreter &interpreter)
2450 interpreter, "target modules dump separate-debug-info",
2451 "List the separate debug info symbol files for one or more target "
2452 "modules.",
2453 nullptr, eCommandRequiresTarget) {}
2454
2456
2457 Options *GetOptions() override { return &m_options; }
2458
2459 class CommandOptions : public Options {
2460 public:
2461 CommandOptions() = default;
2462
2463 ~CommandOptions() override = default;
2464
2465 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
2466 ExecutionContext *execution_context) override {
2467 Status error;
2468 const int short_option = m_getopt_table[option_idx].val;
2469
2470 switch (short_option) {
2471 case 'f':
2472 m_load_all_debug_info.SetCurrentValue(true);
2473 m_load_all_debug_info.SetOptionWasSet();
2474 break;
2475 case 'j':
2476 m_json.SetCurrentValue(true);
2477 m_json.SetOptionWasSet();
2478 break;
2479 case 'e':
2480 m_errors_only.SetCurrentValue(true);
2481 m_errors_only.SetOptionWasSet();
2482 break;
2483 default:
2484 llvm_unreachable("Unimplemented option");
2485 }
2486 return error;
2487 }
2488
2489 void OptionParsingStarting(ExecutionContext *execution_context) override {
2490 m_json.Clear();
2491 m_errors_only.Clear();
2492 m_load_all_debug_info.Clear();
2493 }
2494
2495 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
2496 return llvm::ArrayRef(g_target_modules_dump_separate_debug_info_options);
2497 }
2498
2502 };
2503
2504protected:
2505 void DoExecute(Args &command, CommandReturnObject &result) override {
2506 Target *target = GetTarget();
2507 assert(target && "target guaranteed by eCommandRequiresTarget");
2508 uint32_t num_dumped = 0;
2509
2510 StructuredData::Array separate_debug_info_lists_by_module;
2511 if (command.GetArgumentCount() == 0) {
2512 // Dump all sections for all modules images
2513 const ModuleList &target_modules = target->GetImages();
2514 std::lock_guard<std::recursive_mutex> guard(target_modules.GetMutex());
2515 const size_t num_modules = target_modules.GetSize();
2516 if (num_modules == 0) {
2517 result.AppendError("the target has no associated executable images");
2518 return;
2519 }
2520 for (ModuleSP module_sp : target_modules.ModulesNoLocking()) {
2522 GetDebugger(),
2523 "Interrupted in dumping all "
2524 "separate debug info with {0} of {1} modules dumped",
2525 num_dumped, num_modules))
2526 break;
2527
2528 if (GetSeparateDebugInfoList(separate_debug_info_lists_by_module,
2529 module_sp.get(),
2530 bool(m_options.m_errors_only),
2531 bool(m_options.m_load_all_debug_info)))
2532 num_dumped++;
2533 }
2534 } else {
2535 // Dump specified images (by basename or fullpath)
2536 const char *arg_cstr;
2537 for (int arg_idx = 0;
2538 (arg_cstr = command.GetArgumentAtIndex(arg_idx)) != nullptr;
2539 ++arg_idx) {
2540 ModuleList module_list;
2541 const size_t num_matches =
2542 FindModulesByName(target, arg_cstr, module_list, true);
2543 if (num_matches > 0) {
2544 for (size_t i = 0; i < num_matches; ++i) {
2546 "Interrupted dumping {0} "
2547 "of {1} requested modules",
2548 i, num_matches))
2549 break;
2550 Module *module = module_list.GetModulePointerAtIndex(i);
2551 if (GetSeparateDebugInfoList(separate_debug_info_lists_by_module,
2552 module, bool(m_options.m_errors_only),
2553 bool(m_options.m_load_all_debug_info)))
2554 num_dumped++;
2555 }
2556 } else
2558 "unable to find an image that matches '{0}'", arg_cstr);
2559 }
2560 }
2561
2562 if (num_dumped > 0) {
2563 Stream &strm = result.GetOutputStream();
2564 // Display the debug info files in some format.
2565 if (m_options.m_json) {
2566 // JSON format
2567 separate_debug_info_lists_by_module.Dump(strm,
2568 /*pretty_print=*/true);
2569 } else {
2570 // Human-readable table format
2571 separate_debug_info_lists_by_module.ForEach(
2572 [&result, &strm](StructuredData::Object *obj) {
2573 if (!obj) {
2574 return false;
2575 }
2576
2577 // Each item in `separate_debug_info_lists_by_module` should be a
2578 // valid structured data dictionary.
2579 StructuredData::Dictionary *separate_debug_info_list =
2580 obj->GetAsDictionary();
2581 if (!separate_debug_info_list) {
2582 return false;
2583 }
2584
2585 llvm::StringRef type;
2586 llvm::StringRef symfile;
2587 StructuredData::Array *files;
2588 if (!(separate_debug_info_list->GetValueForKeyAsString("type",
2589 type) &&
2590 separate_debug_info_list->GetValueForKeyAsString("symfile",
2591 symfile) &&
2592 separate_debug_info_list->GetValueForKeyAsArray(
2593 "separate-debug-info-files", files))) {
2594 assert(false);
2595 }
2596
2597 strm << "Symbol file: " << symfile;
2598 strm.EOL();
2599 strm << "Type: \"" << type << "\"";
2600 strm.EOL();
2601 if (type == "dwo") {
2602 DumpDwoFilesTable(strm, *files);
2603 } else if (type == "oso") {
2604 DumpOsoFilesTable(strm, *files);
2605 } else {
2607 "found unsupported debug info type '{0}'", type);
2608 }
2609 return true;
2610 });
2611 }
2613 } else {
2614 result.AppendError("no matching executable images found");
2615 }
2616 }
2617
2619};
2620
2621#pragma mark CommandObjectTargetModulesDump
2622
2623// Dump multi-word command for target modules
2624
2626public:
2627 // Constructors and Destructors
2630 interpreter, "target modules dump",
2631 "Commands for dumping information about one or more target "
2632 "modules.",
2633 "target modules dump "
2634 "[objfile|symtab|sections|ast|symfile|line-table|pcm-info|separate-"
2635 "debug-info] "
2636 "[<file1> <file2> ...]") {
2637 LoadSubCommand("objfile",
2639 new CommandObjectTargetModulesDumpObjfile(interpreter)));
2641 "symtab",
2643 LoadSubCommand("sections",
2645 interpreter)));
2646 LoadSubCommand("symfile",
2648 new CommandObjectTargetModulesDumpSymfile(interpreter)));
2650 "ast", CommandObjectSP(
2651 new CommandObjectTargetModulesDumpClangAST(interpreter)));
2652 LoadSubCommand("line-table",
2654 interpreter)));
2655 LoadSubCommand("separate-debug-info",
2658 interpreter)));
2659 }
2660
2662};
2663
2665public:
2667 : CommandObjectParsed(interpreter, "target modules add",
2668 "Add a new module to the current target's modules.",
2669 "target modules add [<module>]",
2670 eCommandRequiresTarget),
2671 m_symbol_file(LLDB_OPT_SET_1, false, "symfile", 's', 0,
2673 "Fullpath to a stand alone debug "
2674 "symbols file for when debug symbols "
2675 "are not in the executable.") {
2679 m_option_group.Finalize();
2681 }
2682
2684
2685 Options *GetOptions() override { return &m_option_group; }
2686
2687protected:
2691
2692 void DoExecute(Args &args, CommandReturnObject &result) override {
2693 Target *target = GetTarget();
2694 assert(target && "target guaranteed by eCommandRequiresTarget");
2695 bool flush = false;
2696
2697 const size_t argc = args.GetArgumentCount();
2698 if (argc == 0) {
2699 if (m_uuid_option_group.GetOptionValue().OptionWasSet()) {
2700 // We are given a UUID only, go locate the file
2701 ModuleSpec module_spec;
2702 module_spec.GetUUID() =
2703 m_uuid_option_group.GetOptionValue().GetCurrentValue();
2704 if (m_symbol_file.GetOptionValue().OptionWasSet())
2705 module_spec.GetSymbolFileSpec() =
2706 m_symbol_file.GetOptionValue().GetCurrentValue();
2707 Status error;
2709 ModuleSP module_sp(
2710 target->GetOrCreateModule(module_spec, true /* notify */));
2711 if (module_sp) {
2713 return;
2714 } else {
2715 StreamString strm;
2716 module_spec.GetUUID().Dump(strm);
2717 if (module_spec.GetFileSpec()) {
2718 if (module_spec.GetSymbolFileSpec()) {
2719 result.AppendErrorWithFormat(
2720 "Unable to create the executable or symbol file with "
2721 "UUID %s with path %s and symbol file %s",
2722 strm.GetData(), module_spec.GetFileSpec().GetPath().c_str(),
2723 module_spec.GetSymbolFileSpec().GetPath().c_str());
2724 } else {
2725 result.AppendErrorWithFormat(
2726 "Unable to create the executable or symbol file with "
2727 "UUID %s with path %s",
2728 strm.GetData(),
2729 module_spec.GetFileSpec().GetPath().c_str());
2730 }
2731 } else {
2732 result.AppendErrorWithFormat("Unable to create the executable "
2733 "or symbol file with UUID %s",
2734 strm.GetData());
2735 }
2736 return;
2737 }
2738 } else {
2739 StreamString strm;
2740 module_spec.GetUUID().Dump(strm);
2741 result.AppendErrorWithFormat(
2742 "Unable to locate the executable or symbol file with UUID %s",
2743 strm.GetData());
2744 result.SetError(std::move(error));
2745 return;
2746 }
2747 } else {
2748 result.AppendError(
2749 "one or more executable image paths must be specified");
2750 return;
2751 }
2752 } else {
2753 for (auto &entry : args.entries()) {
2754 if (entry.ref().empty())
2755 continue;
2756
2757 FileSpec file_spec(entry.ref());
2758 if (FileSystem::Instance().Exists(file_spec)) {
2759 ModuleSpec module_spec(file_spec);
2760 if (m_uuid_option_group.GetOptionValue().OptionWasSet())
2761 module_spec.GetUUID() =
2762 m_uuid_option_group.GetOptionValue().GetCurrentValue();
2763 if (m_symbol_file.GetOptionValue().OptionWasSet())
2764 module_spec.GetSymbolFileSpec() =
2765 m_symbol_file.GetOptionValue().GetCurrentValue();
2766 if (!module_spec.GetArchitecture().IsValid())
2767 module_spec.GetArchitecture() = target->GetArchitecture();
2768 Status error;
2769 ModuleSP module_sp(target->GetOrCreateModule(
2770 module_spec, true /* notify */, &error));
2771 if (!module_sp) {
2772 const char *error_cstr = error.AsCString();
2773 if (error_cstr)
2774 result.AppendError(error_cstr);
2775 else
2776 result.AppendErrorWithFormat("unsupported module: %s",
2777 entry.c_str());
2778 return;
2779 } else {
2780 flush = true;
2781 }
2783 } else {
2784 std::string resolved_path = file_spec.GetPath();
2785 if (resolved_path != entry.ref()) {
2786 result.AppendErrorWithFormat(
2787 "invalid module path '%s' with resolved path '%s'",
2788 entry.ref().str().c_str(), resolved_path.c_str());
2789 break;
2790 }
2791 result.AppendErrorWithFormat("invalid module path '%s'",
2792 entry.c_str());
2793 break;
2794 }
2795 }
2796 }
2797
2798 if (flush) {
2799 ProcessSP process = target->GetProcessSP();
2800 if (process)
2801 process->Flush();
2802 }
2803 }
2804};
2805
2808public:
2811 interpreter, "target modules load",
2812 "Set the load addresses for one or more sections in a target "
2813 "module.",
2814 "target modules load [--file <module> --uuid <uuid>] <sect-name> "
2815 "<address> [<sect-name> <address> ....]",
2816 eCommandRequiresTarget),
2817 m_file_option(LLDB_OPT_SET_1, false, "file", 'f', 0, eArgTypeName,
2818 "Fullpath or basename for module to load.", ""),
2819 m_load_option(LLDB_OPT_SET_1, false, "load", 'l',
2820 "Write file contents to the memory.", false, true),
2821 m_pc_option(LLDB_OPT_SET_1, false, "set-pc-to-entry", 'p',
2822 "Set PC to the entry point."
2823 " Only applicable with '--load' option.",
2824 false, true),
2825 m_slide_option(LLDB_OPT_SET_1, false, "slide", 's', 0, eArgTypeOffset,
2826 "Set the load address for all sections to be the "
2827 "virtual address in the file plus the offset.",
2828 0) {
2835 m_option_group.Finalize();
2836 }
2837
2839
2840 Options *GetOptions() override { return &m_option_group; }
2841
2842protected:
2843 void DoExecute(Args &args, CommandReturnObject &result) override {
2844 Target *target = GetTarget();
2845 assert(target && "target guaranteed by eCommandRequiresTarget");
2846 const bool load = m_load_option.GetOptionValue().GetCurrentValue();
2847 const bool set_pc = m_pc_option.GetOptionValue().GetCurrentValue();
2848
2849 const size_t argc = args.GetArgumentCount();
2850 ModuleSpec module_spec;
2851 bool search_using_module_spec = false;
2852
2853 // Allow "load" option to work without --file or --uuid option.
2854 if (load) {
2855 if (!m_file_option.GetOptionValue().OptionWasSet() &&
2856 !m_uuid_option_group.GetOptionValue().OptionWasSet()) {
2857 ModuleList &module_list = target->GetImages();
2858 if (module_list.GetSize() == 1) {
2859 search_using_module_spec = true;
2860 module_spec.GetFileSpec() =
2861 module_list.GetModuleAtIndex(0)->GetFileSpec();
2862 }
2863 }
2864 }
2865
2866 if (m_file_option.GetOptionValue().OptionWasSet()) {
2867 search_using_module_spec = true;
2868 const char *arg_cstr = m_file_option.GetOptionValue().GetCurrentValue();
2869 const bool use_global_module_list = true;
2870 ModuleList module_list;
2871 const size_t num_matches = FindModulesByName(
2872 target, arg_cstr, module_list, use_global_module_list);
2873 if (num_matches == 1) {
2874 module_spec.GetFileSpec() =
2875 module_list.GetModuleAtIndex(0)->GetFileSpec();
2876 } else if (num_matches > 1) {
2877 search_using_module_spec = false;
2878 result.AppendErrorWithFormat("more than 1 module matched by name '%s'",
2879 arg_cstr);
2880 } else {
2881 search_using_module_spec = false;
2882 result.AppendErrorWithFormat("no object file for module '%s'",
2883 arg_cstr);
2884 }
2885 }
2886
2887 if (m_uuid_option_group.GetOptionValue().OptionWasSet()) {
2888 search_using_module_spec = true;
2889 module_spec.GetUUID() =
2890 m_uuid_option_group.GetOptionValue().GetCurrentValue();
2891 }
2892
2893 if (search_using_module_spec) {
2894 ModuleList matching_modules;
2895 target->GetImages().FindModules(module_spec, matching_modules);
2896 const size_t num_matches = matching_modules.GetSize();
2897
2898 char path[PATH_MAX];
2899 if (num_matches == 1) {
2900 Module *module = matching_modules.GetModulePointerAtIndex(0);
2901 if (module) {
2902 ObjectFile *objfile = module->GetObjectFile();
2903 if (objfile) {
2904 SectionList *section_list = module->GetSectionList();
2905 if (section_list) {
2906 bool changed = false;
2907 if (argc == 0) {
2908 if (m_slide_option.GetOptionValue().OptionWasSet()) {
2909 const addr_t slide =
2910 m_slide_option.GetOptionValue().GetCurrentValue();
2911 const bool slide_is_offset = true;
2912 module->SetLoadAddress(*target, slide, slide_is_offset,
2913 changed);
2914 } else {
2915 result.AppendError("one or more section name + load "
2916 "address pair must be specified");
2917 return;
2918 }
2919 } else {
2920 if (m_slide_option.GetOptionValue().OptionWasSet()) {
2921 result.AppendError("The \"--slide <offset>\" option can't "
2922 "be used in conjunction with setting "
2923 "section load addresses.\n");
2924 return;
2925 }
2926
2927 for (size_t i = 0; i < argc; i += 2) {
2928 const char *sect_name = args.GetArgumentAtIndex(i);
2929 const char *load_addr_cstr = args.GetArgumentAtIndex(i + 1);
2930 if (sect_name && load_addr_cstr) {
2931 addr_t load_addr;
2932 if (llvm::to_integer(load_addr_cstr, load_addr)) {
2933 SectionSP section_sp(
2934 section_list->FindSectionByName(sect_name));
2935 if (section_sp) {
2936 if (section_sp->IsThreadSpecific()) {
2937 result.AppendErrorWithFormat(
2938 "thread specific sections are not yet "
2939 "supported (section '%s')",
2940 sect_name);
2941 break;
2942 } else {
2943 if (target->SetSectionLoadAddress(section_sp,
2944 load_addr))
2945 changed = true;
2947 "section '{0}' loaded at {1:x}", sect_name,
2948 load_addr);
2949 }
2950 } else {
2951 result.AppendErrorWithFormat("no section found that "
2952 "matches the section "
2953 "name '%s'",
2954 sect_name);
2955 break;
2956 }
2957 } else {
2958 result.AppendErrorWithFormat(
2959 "invalid load address string '%s'", load_addr_cstr);
2960 break;
2961 }
2962 } else {
2963 if (sect_name)
2964 result.AppendError("section names must be followed by "
2965 "a load address.\n");
2966 else
2967 result.AppendError("one or more section name + load "
2968 "address pair must be specified.\n");
2969 break;
2970 }
2971 }
2972 }
2973
2974 if (changed) {
2975 target->ModulesDidLoad(matching_modules);
2976 Process *process = m_exe_ctx.GetProcessPtr();
2977 if (process)
2978 process->Flush();
2979 }
2980 if (load) {
2981 ProcessSP process = target->CalculateProcess();
2982 Address file_entry = objfile->GetEntryPointAddress();
2983 if (!process) {
2984 result.AppendError("No process");
2985 return;
2986 }
2987 if (set_pc && !file_entry.IsValid()) {
2988 result.AppendError("No entry address in object file");
2989 return;
2990 }
2991 std::vector<ObjectFile::LoadableData> loadables(
2992 objfile->GetLoadableData(*target));
2993 if (loadables.size() == 0) {
2994 result.AppendError("No loadable sections");
2995 return;
2996 }
2997 Status error = process->WriteObjectFile(std::move(loadables));
2998 if (error.Fail()) {
2999 result.AppendError(error.AsCString());
3000 return;
3001 }
3002 if (set_pc) {
3003 ThreadList &thread_list = process->GetThreadList();
3004 RegisterContextSP reg_context(
3005 thread_list.GetSelectedThread()->GetRegisterContext());
3006 addr_t file_entry_addr = file_entry.GetLoadAddress(target);
3007 if (!reg_context->SetPC(file_entry_addr)) {
3008 result.AppendErrorWithFormat("failed to set PC value to "
3009 "0x%" PRIx64,
3010 file_entry_addr);
3011 }
3012 }
3013 }
3014 } else {
3015 module->GetFileSpec().GetPath(path, sizeof(path));
3016 result.AppendErrorWithFormat("no sections in object file '%s'",
3017 path);
3018 }
3019 } else {
3020 module->GetFileSpec().GetPath(path, sizeof(path));
3021 result.AppendErrorWithFormat("no object file for module '%s'",
3022 path);
3023 }
3024 } else {
3025 FileSpec *module_spec_file = module_spec.GetFileSpecPtr();
3026 if (module_spec_file) {
3027 module_spec_file->GetPath(path, sizeof(path));
3028 result.AppendErrorWithFormat("invalid module '%s'", path);
3029 } else
3030 result.AppendError("no module spec");
3031 }
3032 } else {
3033 std::string uuid_str;
3034
3035 if (module_spec.GetFileSpec())
3036 module_spec.GetFileSpec().GetPath(path, sizeof(path));
3037 else
3038 path[0] = '\0';
3039
3040 if (module_spec.GetUUIDPtr())
3041 uuid_str = module_spec.GetUUID().GetAsString();
3042 if (num_matches > 1) {
3043 result.AppendErrorWithFormat(
3044 "multiple modules match%s%s%s%s:", path[0] ? " file=" : "", path,
3045 !uuid_str.empty() ? " uuid=" : "", uuid_str.c_str());
3046 for (size_t i = 0; i < num_matches; ++i) {
3047 if (matching_modules.GetModulePointerAtIndex(i)
3048 ->GetFileSpec()
3049 .GetPath(path, sizeof(path)))
3050 result.AppendMessageWithFormatv("{0}", path);
3051 }
3052 } else {
3053 result.AppendErrorWithFormat(
3054 "no modules were found that match%s%s%s%s",
3055 path[0] ? " file=" : "", path, !uuid_str.empty() ? " uuid=" : "",
3056 uuid_str.c_str());
3057 }
3058 }
3059 } else {
3060 result.AppendError("either the \"--file <module>\" or the \"--uuid "
3061 "<uuid>\" option must be specified.\n");
3062 }
3063 if (result.GetStatus() != eReturnStatusFailed)
3065 }
3066
3073};
3074
3075#pragma mark CommandObjectTargetModulesList
3076// List images with associated information
3077#define LLDB_OPTIONS_target_modules_list
3078#include "CommandOptions.inc"
3079
3081public:
3082 class CommandOptions : public Options {
3083 public:
3084 CommandOptions() = default;
3085
3086 ~CommandOptions() override = default;
3087
3088 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
3089 ExecutionContext *execution_context) override {
3090 Status error;
3091
3092 const int short_option = m_getopt_table[option_idx].val;
3093 if (short_option == 'g') {
3095 } else if (short_option == 'a') {
3097 execution_context, option_arg, LLDB_INVALID_ADDRESS, &error);
3098 } else {
3099 unsigned long width = 0;
3100 option_arg.getAsInteger(0, width);
3101 m_format_array.push_back(std::make_pair(short_option, width));
3102 }
3103 return error;
3104 }
3105
3106 void OptionParsingStarting(ExecutionContext *execution_context) override {
3107 m_format_array.clear();
3110 }
3111
3112 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
3113 return llvm::ArrayRef(g_target_modules_list_options);
3114 }
3115
3116 // Instance variables to hold the values for command options.
3117 typedef std::vector<std::pair<char, uint32_t>> FormatWidthCollection;
3121 };
3122
3125 interpreter, "target modules list",
3126 "List current executable and dependent shared library images.",
3127 nullptr, eCommandAllowsDummyTarget) {
3129 }
3130
3132
3133 Options *GetOptions() override { return &m_options; }
3134
3135protected:
3136 void DoExecute(Args &command, CommandReturnObject &result) override {
3137 Target *target = GetTarget();
3138 const bool use_global_module_list = m_options.m_use_global_module_list;
3139
3140 // Every code path other than the global module list needs a real target.
3141 if (!use_global_module_list && (!target || target->IsDummyTarget())) {
3143 return;
3144 }
3145
3146 // Define a local module list here to ensure it lives longer than any
3147 // "locker" object which might lock its contents below (through the
3148 // "module_list_ptr" variable).
3149 ModuleList module_list;
3150 // Dump all sections for all modules images
3151 Stream &strm = result.GetOutputStream();
3152
3153 if (m_options.m_module_addr != LLDB_INVALID_ADDRESS) {
3154 Address module_address;
3155 if (module_address.SetLoadAddress(m_options.m_module_addr, target)) {
3156 ModuleSP module_sp(module_address.GetModule());
3157 if (module_sp) {
3158 PrintModule(*target, module_sp.get(), 0, strm);
3160 } else {
3161 result.AppendErrorWithFormat(
3162 "Couldn't find module matching address: 0x%" PRIx64,
3163 m_options.m_module_addr);
3164 }
3165 } else {
3166 result.AppendErrorWithFormat(
3167 "Couldn't find module containing address: 0x%" PRIx64,
3168 m_options.m_module_addr);
3169 }
3170 return;
3171 }
3172
3173 size_t num_modules = 0;
3174
3175 // This locker will be locked on the mutex in module_list_ptr if it is
3176 // non-nullptr. Otherwise it will lock the
3177 // AllocationModuleCollectionMutex when accessing the global module list
3178 // directly.
3179 std::unique_lock<std::recursive_mutex> guard(
3181
3182 const ModuleList *module_list_ptr = nullptr;
3183 const size_t argc = command.GetArgumentCount();
3184 if (argc == 0) {
3185 if (use_global_module_list) {
3186 guard.lock();
3187 num_modules = Module::GetNumberAllocatedModules();
3188 } else {
3189 module_list_ptr = &target->GetImages();
3190 }
3191 } else {
3192 for (const Args::ArgEntry &arg : command) {
3193 // Dump specified images (by basename or fullpath)
3194 const size_t num_matches = FindModulesByName(
3195 target, arg.c_str(), module_list, use_global_module_list);
3196 if (num_matches == 0) {
3197 if (argc == 1) {
3198 result.AppendErrorWithFormat("no modules found that match '%s'",
3199 arg.c_str());
3200 return;
3201 }
3202 }
3203 }
3204
3205 module_list_ptr = &module_list;
3206 }
3207
3208 std::unique_lock<std::recursive_mutex> lock;
3209 if (module_list_ptr != nullptr) {
3210 lock =
3211 std::unique_lock<std::recursive_mutex>(module_list_ptr->GetMutex());
3212
3213 num_modules = module_list_ptr->GetSize();
3214 }
3215
3216 if (num_modules > 0) {
3217 for (uint32_t image_idx = 0; image_idx < num_modules; ++image_idx) {
3218 ModuleSP module_sp;
3219 Module *module;
3220 if (module_list_ptr) {
3221 module_sp = module_list_ptr->GetModuleAtIndexUnlocked(image_idx);
3222 module = module_sp.get();
3223 } else {
3224 module = Module::GetAllocatedModuleAtIndex(image_idx);
3225 module_sp = module->shared_from_this();
3226 }
3227
3228 const size_t indent = strm.Printf("[%3u] ", image_idx);
3229 PrintModule(*target, module, indent, strm);
3230 }
3232 } else {
3233 if (argc) {
3234 if (use_global_module_list)
3235 result.AppendError(
3236 "the global module list has no matching modules");
3237 else
3238 result.AppendError("the target has no matching modules");
3239 } else {
3240 if (use_global_module_list)
3241 result.AppendError("the global module list is empty");
3242 else
3243 result.AppendError(
3244 "the target has no associated executable images");
3245 }
3246 return;
3247 }
3248 }
3249
3250 void PrintModule(Target &target, Module *module, int indent, Stream &strm) {
3251 if (module == nullptr) {
3252 strm.PutCString("Null module");
3253 return;
3254 }
3255
3256 bool dump_object_name = false;
3257 if (m_options.m_format_array.empty()) {
3258 m_options.m_format_array.push_back(std::make_pair('u', 0));
3259 m_options.m_format_array.push_back(std::make_pair('h', 0));
3260 m_options.m_format_array.push_back(std::make_pair('f', 0));
3261 m_options.m_format_array.push_back(std::make_pair('S', 0));
3262 }
3263 const size_t num_entries = m_options.m_format_array.size();
3264 bool print_space = false;
3265 for (size_t i = 0; i < num_entries; ++i) {
3266 if (print_space)
3267 strm.PutChar(' ');
3268 print_space = true;
3269 const char format_char = m_options.m_format_array[i].first;
3270 uint32_t width = m_options.m_format_array[i].second;
3271 switch (format_char) {
3272 case 'A':
3273 DumpModuleArchitecture(strm, module, false, width);
3274 break;
3275
3276 case 't':
3277 DumpModuleArchitecture(strm, module, true, width);
3278 break;
3279
3280 case 'f':
3281 DumpFullpath(strm, &module->GetFileSpec(), width);
3282 dump_object_name = true;
3283 break;
3284
3285 case 'd':
3286 DumpDirectory(strm, &module->GetFileSpec(), width);
3287 break;
3288
3289 case 'b':
3290 DumpBasename(strm, &module->GetFileSpec(), width);
3291 dump_object_name = true;
3292 break;
3293
3294 case 'h':
3295 case 'o':
3296 // Image header address
3297 {
3298 uint32_t addr_nibble_width =
3299 target.GetArchitecture().GetAddressByteSize() * 2;
3300
3301 ObjectFile *objfile = module->GetObjectFile();
3302 if (objfile) {
3303 Address base_addr(objfile->GetBaseAddress());
3304 if (base_addr.IsValid()) {
3305 if (target.HasLoadedSections()) {
3306 lldb::addr_t load_addr = base_addr.GetLoadAddress(&target);
3307 if (load_addr == LLDB_INVALID_ADDRESS) {
3308 base_addr.Dump(&strm, &target,
3311 } else {
3312 if (format_char == 'o') {
3313 // Show the offset of slide for the image
3314 strm.Printf("0x%*.*" PRIx64, addr_nibble_width,
3315 addr_nibble_width,
3316 load_addr - base_addr.GetFileAddress());
3317 } else {
3318 // Show the load address of the image
3319 strm.Printf("0x%*.*" PRIx64, addr_nibble_width,
3320 addr_nibble_width, load_addr);
3321 }
3322 }
3323 break;
3324 }
3325 // The address was valid, but the image isn't loaded, output the
3326 // address in an appropriate format
3327 base_addr.Dump(&strm, &target, Address::DumpStyleFileAddress);
3328 break;
3329 }
3330 }
3331 strm.Printf("%*s", addr_nibble_width + 2, "");
3332 }
3333 break;
3334
3335 case 'r': {
3336 size_t ref_count = 0;
3337 char in_shared_cache = 'Y';
3338
3339 ModuleSP module_sp(module->shared_from_this());
3340 if (!ModuleList::ModuleIsInCache(module))
3341 in_shared_cache = 'N';
3342 if (module_sp) {
3343 // Take one away to make sure we don't count our local "module_sp"
3344 ref_count = module_sp.use_count() - 1;
3345 }
3346 if (width)
3347 strm.Printf("{%c %*" PRIu64 "}", in_shared_cache, width, (uint64_t)ref_count);
3348 else
3349 strm.Printf("{%c %" PRIu64 "}", in_shared_cache, (uint64_t)ref_count);
3350 } break;
3351
3352 case 's':
3353 case 'S': {
3354 if (const SymbolFile *symbol_file = module->GetSymbolFile()) {
3355 const FileSpec symfile_spec =
3356 symbol_file->GetObjectFile()->GetFileSpec();
3357 if (format_char == 'S') {
3358 // Dump symbol file only if different from module file
3359 if (!symfile_spec || symfile_spec == module->GetFileSpec()) {
3360 print_space = false;
3361 break;
3362 }
3363 // Add a newline and indent past the index
3364 strm.Printf("\n%*s", indent, "");
3365 }
3366 DumpFullpath(strm, &symfile_spec, width);
3367 dump_object_name = true;
3368 break;
3369 }
3370 strm.Printf("%.*s", width, "<NONE>");
3371 } break;
3372
3373 case 'm':
3374 strm.Format("{0:%c}", llvm::fmt_align(module->GetModificationTime(),
3375 llvm::AlignStyle::Left, width));
3376 break;
3377
3378 case 'p':
3379 strm.Printf("%p", static_cast<void *>(module));
3380 break;
3381
3382 case 'u':
3383 DumpModuleUUID(strm, module);
3384 break;
3385
3386 default:
3387 break;
3388 }
3389 }
3390 if (dump_object_name) {
3391 const char *object_name = module->GetObjectName().GetCString();
3392 if (object_name)
3393 strm.Printf("(%s)", object_name);
3394 std::optional<addr_t> memory_addr = module->GetMemoryModuleAddress();
3395 if (memory_addr.has_value())
3396 strm.Printf("(0x%" PRIx64 ")", memory_addr.value());
3397 }
3398 strm.EOL();
3399 }
3400
3402};
3403
3404#pragma mark CommandObjectTargetModulesShowUnwind
3405
3406// Lookup unwind information in images
3407#define LLDB_OPTIONS_target_modules_show_unwind
3408#include "CommandOptions.inc"
3409
3411public:
3412 enum {
3419 };
3420
3421 class CommandOptions : public Options {
3422 public:
3423 CommandOptions() = default;
3424
3425 ~CommandOptions() override = default;
3426
3427 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
3428 ExecutionContext *execution_context) override {
3429 Status error;
3430
3431 const int short_option = m_getopt_table[option_idx].val;
3432
3433 switch (short_option) {
3434 case 'a': {
3435 m_str = std::string(option_arg);
3437 m_addr = OptionArgParser::ToAddress(execution_context, option_arg,
3441 "invalid address string '%s'", option_arg.str().c_str());
3442 break;
3443 }
3444
3445 case 'n':
3446 m_str = std::string(option_arg);
3448 break;
3449
3450 case 'c':
3451 bool value, success;
3452 value = OptionArgParser::ToBoolean(option_arg, false, &success);
3453 if (success) {
3454 m_cached = value;
3455 } else {
3457 "invalid boolean value '{}' passed for -c option", option_arg);
3458 }
3459 break;
3460
3461 default:
3462 llvm_unreachable("Unimplemented option");
3463 }
3464
3465 return error;
3466 }
3467
3468 void OptionParsingStarting(ExecutionContext *execution_context) override {
3470 m_str.clear();
3472 m_cached = false;
3473 }
3474
3475 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
3476 return llvm::ArrayRef(g_target_modules_show_unwind_options);
3477 }
3478
3479 // Instance variables to hold the values for command options.
3480
3481 int m_type = eLookupTypeInvalid; // Should be a eLookupTypeXXX enum after
3482 // parsing options
3483 std::string m_str; // Holds name lookup
3484 lldb::addr_t m_addr = LLDB_INVALID_ADDRESS; // Holds the address to lookup
3485 bool m_cached = true;
3486 };
3487
3490 interpreter, "target modules show-unwind",
3491 "Show synthesized unwind instructions for a function.", nullptr,
3492 eCommandRequiresTarget | eCommandRequiresProcess |
3493 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused) {}
3494
3496
3497 Options *GetOptions() override { return &m_options; }
3498
3499protected:
3500 void DoExecute(Args &command, CommandReturnObject &result) override {
3501 Target *target = m_exe_ctx.GetTargetPtr();
3502 Process *process = m_exe_ctx.GetProcessPtr();
3503 ABI *abi = nullptr;
3504 if (process)
3505 abi = process->GetABI().get();
3506
3507 if (process == nullptr) {
3508 result.AppendError(
3509 "You must have a process running to use this command.");
3510 return;
3511 }
3512
3513 ThreadList threads(process->GetThreadList());
3514 if (threads.GetSize() == 0) {
3515 result.AppendError("the process must be paused to use this command");
3516 return;
3517 }
3518
3519 ThreadSP thread(threads.GetThreadAtIndex(0));
3520 if (!thread) {
3521 result.AppendError("the process must be paused to use this command");
3522 return;
3523 }
3524
3525 SymbolContextList sc_list;
3526
3527 if (m_options.m_type == eLookupTypeFunctionOrSymbol) {
3528 ConstString function_name(m_options.m_str);
3529 ModuleFunctionSearchOptions function_options;
3530 function_options.include_symbols = true;
3531 function_options.include_inlines = false;
3532 target->GetImages().FindFunctions(function_name, eFunctionNameTypeAuto,
3533 function_options, sc_list);
3534 } else if (m_options.m_type == eLookupTypeAddress && target) {
3535 Address addr;
3536 if (target->ResolveLoadAddress(m_options.m_addr, addr)) {
3537 SymbolContext sc;
3538 ModuleSP module_sp(addr.GetModule());
3539 module_sp->ResolveSymbolContextForAddress(addr,
3540 eSymbolContextEverything, sc);
3541 if (sc.function || sc.symbol) {
3542 sc_list.Append(sc);
3543 }
3544 }
3545 } else {
3546 result.AppendError(
3547 "address-expression or function name option must be specified.");
3548 return;
3549 }
3550
3551 if (sc_list.GetSize() == 0) {
3552 result.AppendErrorWithFormat("no unwind data found that matches '%s'",
3553 m_options.m_str.c_str());
3554 return;
3555 }
3556
3557 for (const SymbolContext &sc : sc_list) {
3558 if (sc.symbol == nullptr && sc.function == nullptr)
3559 continue;
3560 if (!sc.module_sp || sc.module_sp->GetObjectFile() == nullptr)
3561 continue;
3562 Address addr = sc.GetFunctionOrSymbolAddress();
3563 if (!addr.IsValid())
3564 continue;
3565 ConstString funcname(sc.GetFunctionName());
3566 if (funcname.IsEmpty())
3567 continue;
3568 addr_t start_addr = addr.GetLoadAddress(target);
3569 if (abi)
3570 start_addr = abi->FixCodeAddress(start_addr);
3571
3572 UnwindTable &uw_table = sc.module_sp->GetUnwindTable();
3573 FuncUnwindersSP func_unwinders_sp =
3574 m_options.m_cached
3575 ? uw_table.GetFuncUnwindersContainingAddress(Address(start_addr),
3576 sc)
3578 Address(start_addr), sc);
3579 if (!func_unwinders_sp)
3580 continue;
3581
3582 result.GetOutputStream().Format(
3583 "UNWIND PLANS for {0}`{1} (start addr {2:x})\n",
3584 sc.module_sp->GetPlatformFileSpec().GetFilename(), funcname,
3585 start_addr);
3586
3587 Args args;
3589 size_t count = args.GetArgumentCount();
3590 for (size_t i = 0; i < count; i++) {
3591 const char *trap_func_name = args.GetArgumentAtIndex(i);
3592 if (strcmp(funcname.GetCString(), trap_func_name) == 0)
3593 result.GetOutputStream().Printf(
3594 "This function is "
3595 "treated as a trap handler function via user setting.\n");
3596 }
3597 PlatformSP platform_sp(target->GetPlatform());
3598 if (platform_sp) {
3599 const std::vector<std::string> &trap_handler_names(
3600 platform_sp->GetTrapHandlerSymbolNames());
3601 for (const std::string &trap_name : trap_handler_names) {
3602 if (llvm::StringRef(trap_name) == funcname) {
3603 result.GetOutputStream().Printf(
3604 "This function's "
3605 "name is listed by the platform as a trap handler.\n");
3606 }
3607 }
3608 }
3609
3610 result.GetOutputStream().Printf("\n");
3611
3612 if (std::shared_ptr<const UnwindPlan> plan_sp =
3613 func_unwinders_sp->GetUnwindPlanAtNonCallSite(*target, *thread)) {
3614 result.GetOutputStream().Format(
3615 "Asynchronous (not restricted to call-sites) UnwindPlan is '{0}'\n",
3616 plan_sp->GetSourceName());
3617 }
3618 if (std::shared_ptr<const UnwindPlan> plan_sp =
3619 func_unwinders_sp->GetUnwindPlanAtCallSite(*target, *thread)) {
3620 result.GetOutputStream().Format(
3621 "Synchronous (restricted to call-sites) UnwindPlan is '{0}'\n",
3622 plan_sp->GetSourceName());
3623 }
3624 if (std::shared_ptr<const UnwindPlan> plan_sp =
3625 func_unwinders_sp->GetUnwindPlanFastUnwind(*target, *thread)) {
3626 result.GetOutputStream().Format("Fast UnwindPlan is '{0}'\n",
3627 plan_sp->GetSourceName());
3628 }
3629
3630 result.GetOutputStream().Printf("\n");
3631
3632 if (std::shared_ptr<const UnwindPlan> plan_sp =
3633 func_unwinders_sp->GetAssemblyUnwindPlan(*target, *thread)) {
3634 result.GetOutputStream().Printf(
3635 "Assembly language inspection UnwindPlan:\n");
3636 plan_sp->Dump(result.GetOutputStream(), thread.get(),
3638 result.GetOutputStream().Printf("\n");
3639 }
3640
3641 if (std::shared_ptr<const UnwindPlan> plan_sp =
3642 func_unwinders_sp->GetObjectFileUnwindPlan(*target)) {
3643 result.GetOutputStream().Printf("object file UnwindPlan:\n");
3644 plan_sp->Dump(result.GetOutputStream(), thread.get(),
3646 result.GetOutputStream().Printf("\n");
3647 }
3648
3649 if (std::shared_ptr<const UnwindPlan> plan_sp =
3650 func_unwinders_sp->GetObjectFileAugmentedUnwindPlan(*target,
3651 *thread)) {
3652 result.GetOutputStream().Printf("object file augmented UnwindPlan:\n");
3653 plan_sp->Dump(result.GetOutputStream(), thread.get(),
3655 result.GetOutputStream().Printf("\n");
3656 }
3657
3658 if (std::shared_ptr<const UnwindPlan> plan_sp =
3659 func_unwinders_sp->GetEHFrameUnwindPlan(*target)) {
3660 result.GetOutputStream().Printf("eh_frame UnwindPlan:\n");
3661 plan_sp->Dump(result.GetOutputStream(), thread.get(),
3663 result.GetOutputStream().Printf("\n");
3664 }
3665
3666 if (std::shared_ptr<const UnwindPlan> plan_sp =
3667 func_unwinders_sp->GetEHFrameAugmentedUnwindPlan(*target,
3668 *thread)) {
3669 result.GetOutputStream().Printf("eh_frame augmented UnwindPlan:\n");
3670 plan_sp->Dump(result.GetOutputStream(), thread.get(),
3672 result.GetOutputStream().Printf("\n");
3673 }
3674
3675 if (std::shared_ptr<const UnwindPlan> plan_sp =
3676 func_unwinders_sp->GetDebugFrameUnwindPlan(*target)) {
3677 result.GetOutputStream().Printf("debug_frame UnwindPlan:\n");
3678 plan_sp->Dump(result.GetOutputStream(), thread.get(),
3680 result.GetOutputStream().Printf("\n");
3681 }
3682
3683 if (std::shared_ptr<const UnwindPlan> plan_sp =
3684 func_unwinders_sp->GetDebugFrameAugmentedUnwindPlan(*target,
3685 *thread)) {
3686 result.GetOutputStream().Printf("debug_frame augmented UnwindPlan:\n");
3687 plan_sp->Dump(result.GetOutputStream(), thread.get(),
3689 result.GetOutputStream().Printf("\n");
3690 }
3691
3692 if (std::shared_ptr<const UnwindPlan> plan_sp =
3693 func_unwinders_sp->GetArmUnwindUnwindPlan(*target)) {
3694 result.GetOutputStream().Printf("ARM.exidx unwind UnwindPlan:\n");
3695 plan_sp->Dump(result.GetOutputStream(), thread.get(),
3697 result.GetOutputStream().Printf("\n");
3698 }
3699
3700 if (std::shared_ptr<const UnwindPlan> plan_sp =
3701 func_unwinders_sp->GetSymbolFileUnwindPlan(*thread)) {
3702 result.GetOutputStream().Printf("Symbol file UnwindPlan:\n");
3703 plan_sp->Dump(result.GetOutputStream(), thread.get(),
3705 result.GetOutputStream().Printf("\n");
3706 }
3707
3708 if (std::shared_ptr<const UnwindPlan> plan_sp =
3709 func_unwinders_sp->GetCompactUnwindUnwindPlan(*target)) {
3710 result.GetOutputStream().Printf("Compact unwind UnwindPlan:\n");
3711 plan_sp->Dump(result.GetOutputStream(), thread.get(),
3713 result.GetOutputStream().Printf("\n");
3714 }
3715
3716 if (std::shared_ptr<const UnwindPlan> plan_sp =
3717 func_unwinders_sp->GetUnwindPlanFastUnwind(*target, *thread)) {
3718 result.GetOutputStream().Printf("Fast UnwindPlan:\n");
3719 plan_sp->Dump(result.GetOutputStream(), thread.get(),
3721 result.GetOutputStream().Printf("\n");
3722 }
3723
3724 ABISP abi_sp = process->GetABI();
3725 if (abi_sp) {
3726 if (UnwindPlanSP plan_sp = abi_sp->CreateDefaultUnwindPlan()) {
3727 assert(((!plan_sp || plan_sp->GetRowCount() == 0 ||
3728 plan_sp->GetRowAtIndex(0)
3729 ->GetUnspecifiedRegistersAreUndefined())) &&
3730 "Default UnwindPlan must set "
3731 "UnspecifiedRegistersAreUndefined to true");
3732 result.GetOutputStream().Printf("Arch default UnwindPlan:\n");
3733 plan_sp->Dump(result.GetOutputStream(), thread.get(),
3735 result.GetOutputStream().Printf("\n");
3736 }
3737
3738 if (UnwindPlanSP plan_sp = abi_sp->CreateFunctionEntryUnwindPlan()) {
3739 result.GetOutputStream().Printf(
3740 "Arch default at entry point UnwindPlan:\n");
3741 plan_sp->Dump(result.GetOutputStream(), thread.get(),
3743 result.GetOutputStream().Printf("\n");
3744 }
3745 }
3746
3747 result.GetOutputStream().Printf("\n");
3748 }
3750 }
3751
3753};
3754
3755// Lookup information in images
3756#define LLDB_OPTIONS_target_modules_lookup
3757#include "CommandOptions.inc"
3758
3760public:
3761 enum {
3765 eLookupTypeFileLine, // Line is optional
3770 };
3771
3772 class CommandOptions : public Options {
3773 public:
3775
3776 ~CommandOptions() override = default;
3777
3778 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
3779 ExecutionContext *execution_context) override {
3780 Status error;
3781
3782 const int short_option = m_getopt_table[option_idx].val;
3783
3784 switch (short_option) {
3785 case 'a': {
3787 m_addr = OptionArgParser::ToAddress(execution_context, option_arg,
3789 } break;
3790
3791 case 'o':
3792 if (option_arg.getAsInteger(0, m_offset))
3794 "invalid offset string '%s'", option_arg.str().c_str());
3795 break;
3796
3797 case 's':
3798 m_str = std::string(option_arg);
3800 break;
3801
3802 case 'f':
3803 m_file.SetFile(option_arg, FileSpec::Style::native);
3805 break;
3806
3807 case 'i':
3808 m_include_inlines = false;
3809 break;
3810
3811 case 'l':
3812 if (option_arg.getAsInteger(0, m_line_number))
3814 "invalid line number string '%s'", option_arg.str().c_str());
3815 else if (m_line_number == 0)
3816 error = Status::FromErrorString("zero is an invalid line number");
3818 break;
3819
3820 case 'F':
3821 m_str = std::string(option_arg);
3823 break;
3824
3825 case 'n':
3826 m_str = std::string(option_arg);
3828 break;
3829
3830 case 't':
3831 m_str = std::string(option_arg);
3833 break;
3834
3835 case 'v':
3836 m_verbose = true;
3837 break;
3838
3839 case 'A':
3840 m_print_all = true;
3841 break;
3842
3843 case 'r':
3844 m_use_regex = true;
3845 break;
3846
3847 case '\x01':
3848 m_all_ranges = true;
3849 break;
3850 default:
3851 llvm_unreachable("Unimplemented option");
3852 }
3853
3854 return error;
3855 }
3856
3857 void OptionParsingStarting(ExecutionContext *execution_context) override {
3859 m_str.clear();
3860 m_file.Clear();
3862 m_offset = 0;
3863 m_line_number = 0;
3864 m_use_regex = false;
3865 m_include_inlines = true;
3866 m_all_ranges = false;
3867 m_verbose = false;
3868 m_print_all = false;
3869 }
3870
3871 Status OptionParsingFinished(ExecutionContext *execution_context) override {
3872 Status status;
3873 if (m_all_ranges && !m_verbose) {
3874 status =
3875 Status::FromErrorString("--show-variable-ranges must be used in "
3876 "conjunction with --verbose.");
3877 }
3878 return status;
3879 }
3880
3881 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
3882 return llvm::ArrayRef(g_target_modules_lookup_options);
3883 }
3884
3885 int m_type; // Should be a eLookupTypeXXX enum after parsing options
3886 std::string m_str; // Holds name lookup
3887 FileSpec m_file; // Files for file lookups
3888 lldb::addr_t m_addr; // Holds the address to lookup
3890 m_offset; // Subtract this offset from m_addr before doing lookups.
3891 uint32_t m_line_number; // Line number for file+line lookups
3892 bool m_use_regex; // Name lookups in m_str are regular expressions.
3893 bool m_include_inlines; // Check for inline entries when looking up by
3894 // file/line.
3895 bool m_all_ranges; // Print all ranges or single range.
3896 bool m_verbose; // Enable verbose lookup info
3897 bool m_print_all; // Print all matches, even in cases where there's a best
3898 // match.
3899 };
3900
3902 : CommandObjectParsed(interpreter, "target modules lookup",
3903 "Look up information within executable and "
3904 "dependent shared library images.",
3905 nullptr, eCommandRequiresTarget) {
3907 }
3908
3910
3911 Options *GetOptions() override { return &m_options; }
3912
3914 bool &syntax_error) {
3915 switch (m_options.m_type) {
3916 case eLookupTypeAddress:
3920 case eLookupTypeSymbol:
3921 default:
3922 return false;
3923 case eLookupTypeType:
3924 break;
3925 }
3926
3927 StackFrameSP frame = m_exe_ctx.GetFrameSP();
3928
3929 if (!frame)
3930 return false;
3931
3932 const SymbolContext &sym_ctx(frame->GetSymbolContext(eSymbolContextModule));
3933
3934 if (!sym_ctx.module_sp)
3935 return false;
3936
3937 switch (m_options.m_type) {
3938 default:
3939 return false;
3940 case eLookupTypeType:
3941 if (!m_options.m_str.empty()) {
3943 *sym_ctx.module_sp, m_options.m_str.c_str(),
3944 m_options.m_use_regex)) {
3946 return true;
3947 }
3948 }
3949 break;
3950 }
3951
3952 return false;
3953 }
3954
3955 bool LookupInModule(CommandInterpreter &interpreter, Module *module,
3956 CommandReturnObject &result, bool &syntax_error) {
3957 switch (m_options.m_type) {
3958 case eLookupTypeAddress:
3959 if (m_options.m_addr != LLDB_INVALID_ADDRESS) {
3961 m_interpreter, result.GetOutputStream(), module,
3962 eSymbolContextEverything |
3963 (m_options.m_verbose
3964 ? static_cast<int>(eSymbolContextVariable)
3965 : 0),
3966 m_options.m_addr, m_options.m_offset, m_options.m_verbose,
3967 m_options.m_all_ranges)) {
3969 return true;
3970 }
3971 }
3972 break;
3973
3974 case eLookupTypeSymbol:
3975 if (!m_options.m_str.empty()) {
3977 module, m_options.m_str.c_str(),
3978 m_options.m_use_regex, m_options.m_verbose,
3979 m_options.m_all_ranges)) {
3981 return true;
3982 }
3983 }
3984 break;
3985
3987 if (m_options.m_file) {
3989 m_interpreter, result.GetOutputStream(), module,
3990 m_options.m_file, m_options.m_line_number,
3991 m_options.m_include_inlines, m_options.m_verbose,
3992 m_options.m_all_ranges)) {
3994 return true;
3995 }
3996 }
3997 break;
3998
4001 if (!m_options.m_str.empty()) {
4002 ModuleFunctionSearchOptions function_options;
4003 function_options.include_symbols =
4005 function_options.include_inlines = m_options.m_include_inlines;
4006
4008 module, m_options.m_str.c_str(),
4009 m_options.m_use_regex, function_options,
4010 m_options.m_verbose,
4011 m_options.m_all_ranges)) {
4013 return true;
4014 }
4015 }
4016 break;
4017
4018 case eLookupTypeType:
4019 if (!m_options.m_str.empty()) {
4021 GetTarget(), m_interpreter, result.GetOutputStream(), module,
4022 m_options.m_str.c_str(), m_options.m_use_regex)) {
4024 return true;
4025 }
4026 }
4027 break;
4028
4029 default:
4030 m_options.GenerateOptionUsage(
4031 result.GetErrorStream(), *this,
4032 GetCommandInterpreter().GetDebugger().GetTerminalWidth(),
4033 GetCommandInterpreter().GetDebugger().GetUseColor());
4034 syntax_error = true;
4035 break;
4036 }
4037
4039 return false;
4040 }
4041
4042protected:
4043 void DoExecute(Args &command, CommandReturnObject &result) override {
4044 Target *target = GetTarget();
4045 assert(target && "target guaranteed by eCommandRequiresTarget");
4046 bool syntax_error = false;
4047 uint32_t i;
4048 uint32_t num_successful_lookups = 0;
4049 // Dump all sections for all modules images
4050
4051 if (command.GetArgumentCount() == 0) {
4052 // Where it is possible to look in the current symbol context first,
4053 // try that. If this search was successful and --all was not passed,
4054 // don't print anything else.
4055 if (LookupHere(m_interpreter, result, syntax_error)) {
4056 result.GetOutputStream().EOL();
4057 num_successful_lookups++;
4058 if (!m_options.m_print_all) {
4060 return;
4061 }
4062 }
4063
4064 // Dump all sections for all other modules
4065
4066 const ModuleList &target_modules = target->GetImages();
4067 std::lock_guard<std::recursive_mutex> guard(target_modules.GetMutex());
4068 if (target_modules.GetSize() == 0) {
4069 result.AppendError("the target has no associated executable images");
4070 return;
4071 }
4072
4073 for (ModuleSP module_sp : target_modules.ModulesNoLocking()) {
4074 if (LookupInModule(m_interpreter, module_sp.get(), result,
4075 syntax_error)) {
4076 result.GetOutputStream().EOL();
4077 num_successful_lookups++;
4078 }
4079 }
4080 } else {
4081 // Dump specified images (by basename or fullpath)
4082 const char *arg_cstr;
4083 for (i = 0; (arg_cstr = command.GetArgumentAtIndex(i)) != nullptr &&
4084 !syntax_error;
4085 ++i) {
4086 ModuleList module_list;
4087 const size_t num_matches =
4088 FindModulesByName(target, arg_cstr, module_list, false);
4089 if (num_matches > 0) {
4090 for (size_t j = 0; j < num_matches; ++j) {
4091 Module *module = module_list.GetModulePointerAtIndex(j);
4092 if (module) {
4093 if (LookupInModule(m_interpreter, module, result, syntax_error)) {
4094 result.GetOutputStream().EOL();
4095 num_successful_lookups++;
4096 }
4097 }
4098 }
4099 } else
4101 "unable to find an image that matches '{0}'", arg_cstr);
4102 }
4103 }
4104
4105 if (num_successful_lookups > 0)
4107 else
4109 }
4110
4112};
4113
4114#pragma mark CommandObjectMultiwordImageSearchPaths
4115
4116// CommandObjectMultiwordImageSearchPaths
4117
4119 : public CommandObjectMultiword {
4120public:
4123 interpreter, "target modules search-paths",
4124 "Commands for managing module search paths for a target.",
4125 "target modules search-paths <subcommand> [<subcommand-options>]") {
4127 "add", CommandObjectSP(
4131 interpreter)));
4133 "insert",
4138 interpreter)));
4141 interpreter)));
4142 }
4143
4145};
4146
4147#pragma mark CommandObjectTargetModules
4148
4149// CommandObjectTargetModules
4150
4152public:
4153 // Constructors and Destructors
4155 : CommandObjectMultiword(interpreter, "target modules",
4156 "Commands for accessing information for one or "
4157 "more target modules.",
4158 "target modules <sub-command> ...") {
4160 "add", CommandObjectSP(new CommandObjectTargetModulesAdd(interpreter)));
4162 interpreter)));
4164 interpreter)));
4166 interpreter)));
4168 "lookup",
4171 "search-paths",
4175 "show-unwind",
4177 }
4178
4179 ~CommandObjectTargetModules() override = default;
4180
4181private:
4182 // For CommandObjectTargetModules only
4186};
4187
4189public:
4192 interpreter, "target symbols add",
4193 "Add a debug symbol file to one of the target's current modules by "
4194 "specifying a path to a debug symbols file or by using the options "
4195 "to specify a module.",
4196 "target symbols add <cmd-options> [<symfile>]",
4197 eCommandRequiresTarget),
4199 LLDB_OPT_SET_1, false, "shlib", 's', lldb::eModuleCompletion,
4201 "Locate the debug symbols for the shared library specified by "
4202 "name."),
4204 LLDB_OPT_SET_2, false, "frame", 'F',
4205 "Locate the debug symbols for the currently selected frame.", false,
4206 true),
4207 m_current_stack_option(LLDB_OPT_SET_2, false, "stack", 'S',
4208 "Locate the debug symbols for every frame in "
4209 "the current call stack.",
4210 false, true)
4211
4212 {
4220 m_option_group.Finalize();
4222 }
4223
4225
4226 Options *GetOptions() override { return &m_option_group; }
4227
4228protected:
4229 bool AddModuleSymbols(Target *target, ModuleSpec &module_spec, bool &flush,
4230 CommandReturnObject &result) {
4231 const FileSpec &symbol_fspec = module_spec.GetSymbolFileSpec();
4232 if (!symbol_fspec) {
4233 result.AppendError(
4234 "one or more executable image paths must be specified");
4235 return false;
4236 }
4237
4238 char symfile_path[PATH_MAX];
4239 symbol_fspec.GetPath(symfile_path, sizeof(symfile_path));
4240
4241 if (!module_spec.GetUUID().IsValid()) {
4242 if (!module_spec.GetFileSpec() && !module_spec.GetPlatformFileSpec())
4243 module_spec.GetFileSpec().SetFilename(symbol_fspec.GetFilename());
4244 }
4245
4246 // Now module_spec represents a symbol file for a module that might exist
4247 // in the current target. Let's find possible matches.
4248 ModuleList matching_modules;
4249
4250 // First extract all module specs from the symbol file
4251 lldb_private::ModuleSpecList symfile_module_specs =
4253 0);
4254 if (symfile_module_specs.GetSize() > 0) {
4255 // Now extract the module spec that matches the target architecture
4256 ModuleSpec target_arch_module_spec;
4257 ModuleSpec symfile_module_spec;
4258 target_arch_module_spec.GetArchitecture() = target->GetArchitecture();
4259 if (symfile_module_specs.FindMatchingModuleSpec(target_arch_module_spec,
4260 symfile_module_spec)) {
4261 if (symfile_module_spec.GetUUID().IsValid()) {
4262 // It has a UUID, look for this UUID in the target modules
4263 ModuleSpec symfile_uuid_module_spec;
4264 symfile_uuid_module_spec.GetUUID() = symfile_module_spec.GetUUID();
4265 target->GetImages().FindModules(symfile_uuid_module_spec,
4266 matching_modules);
4267 }
4268 }
4269
4270 if (matching_modules.IsEmpty()) {
4271 // No matches yet. Iterate through the module specs to find a UUID
4272 // value that we can match up to an image in our target.
4273 const size_t num_symfile_module_specs = symfile_module_specs.GetSize();
4274 for (size_t i = 0;
4275 i < num_symfile_module_specs && matching_modules.IsEmpty(); ++i) {
4276 if (symfile_module_specs.GetModuleSpecAtIndex(
4277 i, symfile_module_spec)) {
4278 if (symfile_module_spec.GetUUID().IsValid()) {
4279 // It has a UUID. Look for this UUID in the target modules.
4280 ModuleSpec symfile_uuid_module_spec;
4281 symfile_uuid_module_spec.GetUUID() =
4282 symfile_module_spec.GetUUID();
4283 target->GetImages().FindModules(symfile_uuid_module_spec,
4284 matching_modules);
4285 }
4286 }
4287 }
4288 }
4289 }
4290
4291 // Just try to match up the file by basename if we have no matches at
4292 // this point. For example, module foo might have symbols in foo.debug.
4293 if (matching_modules.IsEmpty())
4294 target->GetImages().FindModules(module_spec, matching_modules);
4295
4296 while (matching_modules.IsEmpty()) {
4297 ConstString filename_no_extension(
4299 // Empty string returned, let's bail
4300 if (!filename_no_extension)
4301 break;
4302
4303 // Check if there was no extension to strip and the basename is the same
4304 if (filename_no_extension == module_spec.GetFileSpec().GetFilename())
4305 break;
4306
4307 // Replace basename with one fewer extension
4308 module_spec.GetFileSpec().SetFilename(filename_no_extension);
4309 target->GetImages().FindModules(module_spec, matching_modules);
4310 }
4311
4312 if (matching_modules.GetSize() > 1) {
4313 result.AppendErrorWithFormat("multiple modules match symbol file '%s', "
4314 "use the --uuid option to resolve the "
4315 "ambiguity",
4316 symfile_path);
4317 return false;
4318 }
4319
4320 if (matching_modules.GetSize() == 1) {
4321 ModuleSP module_sp(matching_modules.GetModuleAtIndex(0));
4322
4323 // The module has not yet created its symbol vendor, we can just give
4324 // the existing target module the symfile path to use for when it
4325 // decides to create it!
4326 module_sp->SetSymbolFileFileSpec(symbol_fspec);
4327
4328 SymbolFile *symbol_file =
4329 module_sp->GetSymbolFile(true, &result.GetErrorStream());
4330 if (symbol_file) {
4331 ObjectFile *object_file = symbol_file->GetObjectFile();
4332 if (object_file && object_file->GetFileSpec() == symbol_fspec) {
4333 // Provide feedback that the symfile has been successfully added.
4334 const FileSpec &module_fs = module_sp->GetFileSpec();
4336 "symbol file '{0}' has been added to '{1}'", symfile_path,
4337 module_fs.GetPath().c_str());
4338
4339 // Let clients know something changed in the module if it is
4340 // currently loaded
4341 ModuleList module_list;
4342 module_list.Append(module_sp);
4343 target->SymbolsDidLoad(module_list);
4344
4345 // Make sure we load any scripting resources that may be embedded
4346 // in the debug info files in case the platform supports that.
4347 std::list<Status> errors;
4348 module_list.LoadScriptingResourcesInTarget(target, errors);
4349 for (const auto &err : errors)
4350 result.AppendWarning(err.AsCString());
4351
4352 flush = true;
4354 return true;
4355 }
4356 }
4357 // Clear the symbol file spec if anything went wrong
4358 module_sp->SetSymbolFileFileSpec(FileSpec());
4359 }
4360
4361 StreamString ss_symfile_uuid;
4362 if (module_spec.GetUUID().IsValid()) {
4363 ss_symfile_uuid << " (";
4364 module_spec.GetUUID().Dump(ss_symfile_uuid);
4365 ss_symfile_uuid << ')';
4366 }
4367 result.AppendErrorWithFormat(
4368 "symbol file '%s'%s does not match any existing module%s", symfile_path,
4369 ss_symfile_uuid.GetData(),
4370 !llvm::sys::fs::is_regular_file(symbol_fspec.GetPath())
4371 ? "\n please specify the full path to the symbol file"
4372 : "");
4373 return false;
4374 }
4375
4377 CommandReturnObject &result, bool &flush) {
4378 Status error;
4380 if (module_spec.GetSymbolFileSpec())
4381 return AddModuleSymbols(m_exe_ctx.GetTargetPtr(), module_spec, flush,
4382 result);
4383 } else {
4384 result.SetError(std::move(error));
4385 }
4386 return false;
4387 }
4388
4389 bool AddSymbolsForUUID(CommandReturnObject &result, bool &flush) {
4390 assert(m_uuid_option_group.GetOptionValue().OptionWasSet());
4391
4392 ModuleSpec module_spec;
4393 module_spec.GetUUID() =
4394 m_uuid_option_group.GetOptionValue().GetCurrentValue();
4395
4396 if (!DownloadObjectAndSymbolFile(module_spec, result, flush)) {
4397 StreamString error_strm;
4398 error_strm.PutCString("unable to find debug symbols for UUID ");
4399 module_spec.GetUUID().Dump(error_strm);
4400 result.AppendError(error_strm.GetString());
4401 return false;
4402 }
4403
4404 return true;
4405 }
4406
4407 bool AddSymbolsForFile(CommandReturnObject &result, bool &flush) {
4408 assert(m_file_option.GetOptionValue().OptionWasSet());
4409
4410 ModuleSpec module_spec;
4411 module_spec.GetFileSpec() =
4412 m_file_option.GetOptionValue().GetCurrentValue();
4413
4414 Target *target = m_exe_ctx.GetTargetPtr();
4415
4416 ModuleSP module_sp(target->GetImages().FindFirstModule(module_spec));
4417 if (module_sp) {
4418 module_spec.GetFileSpec() = module_sp->GetFileSpec();
4419 module_spec.GetPlatformFileSpec() = module_sp->GetPlatformFileSpec();
4420 module_spec.GetUUID() = module_sp->GetUUID();
4421 module_spec.GetArchitecture() = module_sp->GetArchitecture();
4422 } else {
4423 module_spec.GetArchitecture() = target->GetArchitecture();
4424 }
4425
4426 if (!DownloadObjectAndSymbolFile(module_spec, result, flush)) {
4427 StreamString error_strm;
4428 error_strm.PutCString(
4429 "unable to find debug symbols for the executable file ");
4430 error_strm << module_spec.GetFileSpec();
4431 result.AppendError(error_strm.GetString());
4432 return false;
4433 }
4434
4435 return true;
4436 }
4437
4438 bool AddSymbolsForFrame(CommandReturnObject &result, bool &flush) {
4439 assert(m_current_frame_option.GetOptionValue().OptionWasSet());
4440
4441 Process *process = m_exe_ctx.GetProcessPtr();
4442 if (!process) {
4443 result.AppendError(
4444 "a process must exist in order to use the --frame option");
4445 return false;
4446 }
4447
4448 const StateType process_state = process->GetState();
4449 if (!StateIsStoppedState(process_state, true)) {
4450 result.AppendErrorWithFormat("process is not stopped: %s",
4451 StateAsCString(process_state));
4452 return false;
4453 }
4454
4455 StackFrame *frame = m_exe_ctx.GetFramePtr();
4456 if (!frame) {
4457 result.AppendError("invalid current frame");
4458 return false;
4459 }
4460
4461 ModuleSP frame_module_sp(
4462 frame->GetSymbolContext(eSymbolContextModule).module_sp);
4463 if (!frame_module_sp) {
4464 result.AppendError("frame has no module");
4465 return false;
4466 }
4467
4468 ModuleSpec module_spec;
4469 module_spec.GetUUID() = frame_module_sp->GetUUID();
4470 module_spec.GetArchitecture() = frame_module_sp->GetArchitecture();
4471 module_spec.GetFileSpec() = frame_module_sp->GetPlatformFileSpec();
4472
4473 if (!DownloadObjectAndSymbolFile(module_spec, result, flush)) {
4474 result.AppendError("unable to find debug symbols for the current frame");
4475 return false;
4476 }
4477
4478 return true;
4479 }
4480
4481 bool AddSymbolsForStack(CommandReturnObject &result, bool &flush) {
4482 assert(m_current_stack_option.GetOptionValue().OptionWasSet());
4483
4484 Process *process = m_exe_ctx.GetProcessPtr();
4485 if (!process) {
4486 result.AppendError(
4487 "a process must exist in order to use the --stack option");
4488 return false;
4489 }
4490
4491 const StateType process_state = process->GetState();
4492 if (!StateIsStoppedState(process_state, true)) {
4493 result.AppendErrorWithFormat("process is not stopped: %s",
4494 StateAsCString(process_state));
4495 return false;
4496 }
4497
4498 Thread *thread = m_exe_ctx.GetThreadPtr();
4499 if (!thread) {
4500 result.AppendError("invalid current thread");
4501 return false;
4502 }
4503
4504 bool symbols_found = false;
4505 uint32_t frame_count = thread->GetStackFrameCount();
4506 for (uint32_t i = 0; i < frame_count; ++i) {
4507 lldb::StackFrameSP frame_sp = thread->GetStackFrameAtIndex(i);
4508
4509 ModuleSP frame_module_sp(
4510 frame_sp->GetSymbolContext(eSymbolContextModule).module_sp);
4511 if (!frame_module_sp)
4512 continue;
4513
4514 ModuleSpec module_spec;
4515 module_spec.GetUUID() = frame_module_sp->GetUUID();
4516 module_spec.GetFileSpec() = frame_module_sp->GetPlatformFileSpec();
4517 module_spec.GetArchitecture() = frame_module_sp->GetArchitecture();
4518
4519 bool current_frame_flush = false;
4520 if (DownloadObjectAndSymbolFile(module_spec, result, current_frame_flush))
4521 symbols_found = true;
4522 flush |= current_frame_flush;
4523 }
4524
4525 if (!symbols_found) {
4526 result.AppendError(
4527 "unable to find debug symbols in the current call stack");
4528 return false;
4529 }
4530
4531 return true;
4532 }
4533
4534 void DoExecute(Args &args, CommandReturnObject &result) override {
4535 Target *target = m_exe_ctx.GetTargetPtr();
4537 bool flush = false;
4538 ModuleSpec module_spec;
4539 const bool uuid_option_set =
4540 m_uuid_option_group.GetOptionValue().OptionWasSet();
4541 const bool file_option_set = m_file_option.GetOptionValue().OptionWasSet();
4542 const bool frame_option_set =
4543 m_current_frame_option.GetOptionValue().OptionWasSet();
4544 const bool stack_option_set =
4545 m_current_stack_option.GetOptionValue().OptionWasSet();
4546 const size_t argc = args.GetArgumentCount();
4547
4548 if (argc == 0) {
4549 if (uuid_option_set)
4550 AddSymbolsForUUID(result, flush);
4551 else if (file_option_set)
4552 AddSymbolsForFile(result, flush);
4553 else if (frame_option_set)
4554 AddSymbolsForFrame(result, flush);
4555 else if (stack_option_set)
4556 AddSymbolsForStack(result, flush);
4557 else
4558 result.AppendError("one or more symbol file paths must be specified, "
4559 "or options must be specified");
4560 } else {
4561 if (uuid_option_set) {
4562 result.AppendError("specify either one or more paths to symbol files "
4563 "or use the --uuid option without arguments");
4564 } else if (frame_option_set) {
4565 result.AppendError("specify either one or more paths to symbol files "
4566 "or use the --frame option without arguments");
4567 } else if (file_option_set && argc > 1) {
4568 result.AppendError("specify at most one symbol file path when "
4569 "--shlib option is set");
4570 } else {
4571 PlatformSP platform_sp(target->GetPlatform());
4572
4573 for (auto &entry : args.entries()) {
4574 if (!entry.ref().empty()) {
4575 auto &symbol_file_spec = module_spec.GetSymbolFileSpec();
4576 symbol_file_spec.SetFile(entry.ref(), FileSpec::Style::native);
4577 FileSystem::Instance().Resolve(symbol_file_spec);
4578 if (file_option_set) {
4579 module_spec.GetFileSpec() =
4580 m_file_option.GetOptionValue().GetCurrentValue();
4581 }
4582 if (platform_sp) {
4583 FileSpec symfile_spec;
4584 if (platform_sp
4585 ->ResolveSymbolFile(*target, module_spec, symfile_spec)
4586 .Success())
4587 module_spec.GetSymbolFileSpec() = symfile_spec;
4588 }
4589
4590 bool symfile_exists =
4592
4593 if (symfile_exists) {
4594 if (!AddModuleSymbols(target, module_spec, flush, result))
4595 break;
4596 } else {
4597 std::string resolved_symfile_path =
4598 module_spec.GetSymbolFileSpec().GetPath();
4599 if (resolved_symfile_path != entry.ref()) {
4600 result.AppendErrorWithFormat(
4601 "invalid module path '%s' with resolved path '%s'",
4602 entry.c_str(), resolved_symfile_path.c_str());
4603 break;
4604 }
4605 result.AppendErrorWithFormat("invalid module path '%s'",
4606 entry.c_str());
4607 break;
4608 }
4609 }
4610 }
4611 }
4612 }
4613
4614 if (flush) {
4615 Process *process = m_exe_ctx.GetProcessPtr();
4616 if (process)
4617 process->Flush();
4618 }
4619 }
4620
4626};
4627
4628#pragma mark CommandObjectTargetSymbols
4629
4630// CommandObjectTargetSymbols
4631
4633public:
4634 // Constructors and Destructors
4637 interpreter, "target symbols",
4638 "Commands for adding and managing debug symbol files.",
4639 "target symbols <sub-command> ...") {
4641 "add", CommandObjectSP(new CommandObjectTargetSymbolsAdd(interpreter)));
4642 }
4643
4644 ~CommandObjectTargetSymbols() override = default;
4645
4646private:
4647 // For CommandObjectTargetModules only
4651};
4652
4653#pragma mark CommandObjectTargetStopHookAdd
4654
4655// CommandObjectTargetStopHookAdd
4656#define LLDB_OPTIONS_target_stop_hook_add
4657#include "CommandOptions.inc"
4658
4661public:
4663 public:
4665
4666 ~CommandOptions() override = default;
4667
4668 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
4669 return llvm::ArrayRef(g_target_stop_hook_add_options);
4670 }
4671
4672 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
4673 ExecutionContext *execution_context) override {
4674 Status error;
4675 const int short_option =
4676 g_target_stop_hook_add_options[option_idx].short_option;
4677
4678 switch (short_option) {
4679 case 'c':
4680 m_class_name = std::string(option_arg);
4681 m_sym_ctx_specified = true;
4682 break;
4683
4684 case 'e':
4685 if (option_arg.getAsInteger(0, m_line_end)) {
4687 "invalid end line number: \"%s\"", option_arg.str().c_str());
4688 break;
4689 }
4690 m_sym_ctx_specified = true;
4691 break;
4692
4693 case 'G': {
4694 bool value, success;
4695 value = OptionArgParser::ToBoolean(option_arg, false, &success);
4696 if (success) {
4697 m_auto_continue = value;
4698 } else
4700 "invalid boolean value '%s' passed for -G option",
4701 option_arg.str().c_str());
4702 } break;
4703 case 'l':
4704 if (option_arg.getAsInteger(0, m_line_start)) {
4706 "invalid start line number: \"%s\"", option_arg.str().c_str());
4707 break;
4708 }
4709 m_sym_ctx_specified = true;
4710 break;
4711
4712 case 'i':
4713 m_no_inlines = true;
4714 break;
4715
4716 case 'n':
4717 m_function_name = std::string(option_arg);
4718 m_func_name_type_mask |= eFunctionNameTypeAuto;
4719 m_sym_ctx_specified = true;
4720 break;
4721
4722 case 'f':
4723 m_file_name = std::string(option_arg);
4724 m_sym_ctx_specified = true;
4725 break;
4726
4727 case 's':
4728 m_module_name = std::string(option_arg);
4729 m_sym_ctx_specified = true;
4730 break;
4731
4732 case 't':
4733 if (option_arg.getAsInteger(0, m_thread_id))
4735 "invalid thread id string '%s'", option_arg.str().c_str());
4736 m_thread_specified = true;
4737 break;
4738
4739 case 'T':
4740 m_thread_name = std::string(option_arg);
4741 m_thread_specified = true;
4742 break;
4743
4744 case 'q':
4745 m_queue_name = std::string(option_arg);
4746 m_thread_specified = true;
4747 break;
4748
4749 case 'x':
4750 if (option_arg.getAsInteger(0, m_thread_index))
4752 "invalid thread index string '%s'", option_arg.str().c_str());
4753 m_thread_specified = true;
4754 break;
4755
4756 case 'o':
4757 m_use_one_liner = true;
4758 m_one_liner.push_back(std::string(option_arg));
4759 break;
4760
4761 case 'I': {
4762 bool value, success;
4763 value = OptionArgParser::ToBoolean(option_arg, false, &success);
4764 if (success)
4765 m_at_initial_stop = value;
4766 else
4768 "invalid boolean value '%s' passed for -F option",
4769 option_arg.str().c_str());
4770 } break;
4771
4772 default:
4773 llvm_unreachable("Unimplemented option");
4774 }
4775 return error;
4776 }
4777
4778 void OptionParsingStarting(ExecutionContext *execution_context) override {
4779 m_class_name.clear();
4780 m_function_name.clear();
4781 m_line_start = 0;
4783 m_file_name.clear();
4784 m_module_name.clear();
4785 m_func_name_type_mask = eFunctionNameTypeAuto;
4788 m_thread_name.clear();
4789 m_queue_name.clear();
4790
4791 m_no_inlines = false;
4792 m_sym_ctx_specified = false;
4793 m_thread_specified = false;
4794
4795 m_use_one_liner = false;
4796 m_one_liner.clear();
4797 m_auto_continue = false;
4798 m_at_initial_stop = true;
4799 }
4800
4801 std::string m_class_name;
4802 std::string m_function_name;
4803 uint32_t m_line_start = 0;
4805 std::string m_file_name;
4806 std::string m_module_name;
4808 eFunctionNameTypeAuto; // A pick from lldb::FunctionNameType.
4811 std::string m_thread_name;
4812 std::string m_queue_name;
4814 bool m_no_inlines = false;
4816 // Instance variables to hold the values for one_liner options.
4817 bool m_use_one_liner = false;
4818 std::vector<std::string> m_one_liner;
4820
4821 bool m_auto_continue = false;
4822 };
4823
4825 : CommandObjectParsed(interpreter, "target stop-hook add",
4826 "Add a hook to be executed when the target stops."
4827 "The hook can either be a list of commands or an "
4828 "appropriately defined Python class. You can also "
4829 "add filters so the hook only runs a certain stop "
4830 "points.",
4831 "target stop-hook add", eCommandAllowsDummyTarget),
4834 m_python_class_options("scripted stop-hook", true, 'P') {
4836 R"(
4837Command Based stop-hooks:
4838-------------------------
4839 Stop hooks can run a list of lldb commands by providing one or more
4840 --one-liner options. The commands will get run in the order they are added.
4841 Or you can provide no commands, in which case you will enter a command editor
4842 where you can enter the commands to be run.
4843
4844Python Based Stop Hooks:
4845------------------------
4846 Stop hooks can be implemented with a suitably defined Python class, whose name
4847 is passed in the --python-class option.
4848
4849 When the stop hook is added, the class is initialized by calling:
4850
4851 def __init__(self, target, extra_args, internal_dict):
4852
4853 target: The target that the stop hook is being added to.
4854 extra_args: An SBStructuredData Dictionary filled with the -key -value
4855 option pairs passed to the command.
4856 dict: An implementation detail provided by lldb.
4857
4858 Then when the stop-hook triggers, lldb will run the 'handle_stop' method.
4859 The method has the signature:
4861 def handle_stop(self, exe_ctx, stream):
4862
4863 exe_ctx: An SBExecutionContext for the thread that has stopped.
4864 stream: An SBStream, anything written to this stream will be printed in the
4865 the stop message when the process stops.
4866
4867 Return Value: The method returns "should_stop". If should_stop is false
4868 from all the stop hook executions on threads that stopped
4869 with a reason, then the process will continue. Note that this
4870 will happen only after all the stop hooks are run.
4871
4872Filter Options:
4873---------------
4874 Stop hooks can be set to always run, or to only run when the stopped thread
4875 matches the filter options passed on the command line. The available filter
4876 options include a shared library or a thread or queue specification,
4877 a line range in a source file, a function name or a class name.
4878 )");
4881 LLDB_OPT_SET_FROM_TO(4, 6));
4882 m_all_options.Append(&m_options);
4883 m_all_options.Finalize();
4884 }
4885
4886 ~CommandObjectTargetStopHookAdd() override = default;
4887
4888 Options *GetOptions() override { return &m_all_options; }
4889
4890protected:
4891 void IOHandlerActivated(IOHandler &io_handler, bool interactive) override {
4892 if (interactive) {
4893 if (lldb::LockableStreamFileSP output_sp =
4894 io_handler.GetOutputStreamFileSP()) {
4895 LockedStreamFile locked_stream = output_sp->Lock();
4896 locked_stream.PutCString(
4897 "Enter your stop hook command(s). Type 'DONE' to end.\n");
4898 }
4899 }
4900 }
4901
4902 void IOHandlerInputComplete(IOHandler &io_handler,
4903 std::string &line) override {
4904 if (m_stop_hook_sp) {
4905 if (line.empty()) {
4906 if (lldb::LockableStreamFileSP error_sp =
4907 io_handler.GetErrorStreamFileSP()) {
4908 LockedStreamFile locked_stream = error_sp->Lock();
4909 locked_stream.Printf("error: stop hook #%" PRIu64
4910 " aborted, no commands.\n",
4911 m_stop_hook_sp->GetID());
4912 }
4914 } else {
4915 // The IOHandler editor is only for command lines stop hooks:
4916 Target::StopHookCommandLine *hook_ptr =
4917 static_cast<Target::StopHookCommandLine *>(m_stop_hook_sp.get());
4918
4919 hook_ptr->SetActionFromString(line);
4920 if (lldb::LockableStreamFileSP output_sp =
4921 io_handler.GetOutputStreamFileSP()) {
4922 LockedStreamFile locked_stream = output_sp->Lock();
4923 locked_stream.Printf("Stop hook #%" PRIu64 " added.\n",
4924 m_stop_hook_sp->GetID());
4925 }
4926 }
4927 m_stop_hook_sp.reset();
4928 }
4929 io_handler.SetIsDone(true);
4930 }
4931
4932 void DoExecute(Args &command, CommandReturnObject &result) override {
4933 m_stop_hook_sp.reset();
4934
4935 Target *target = GetTarget();
4936 assert(target && "target guaranteed by eCommandRequiresTarget");
4937 Target::StopHookSP new_hook_sp = target->CreateStopHook(
4938 m_python_class_options.GetName().empty()
4939 ? Target::StopHook::StopHookKind::CommandBased
4940 : Target::StopHook::StopHookKind::ScriptBased);
4941
4942 // First step, make the specifier.
4943 std::unique_ptr<SymbolContextSpecifier> specifier_up;
4944 if (m_options.m_sym_ctx_specified) {
4945 specifier_up =
4946 std::make_unique<SymbolContextSpecifier>(target->shared_from_this());
4947
4948 if (!m_options.m_module_name.empty()) {
4949 specifier_up->AddSpecification(
4950 m_options.m_module_name.c_str(),
4952 }
4953
4954 if (!m_options.m_class_name.empty()) {
4955 specifier_up->AddSpecification(
4956 m_options.m_class_name.c_str(),
4958 }
4959
4960 if (!m_options.m_file_name.empty()) {
4961 specifier_up->AddSpecification(m_options.m_file_name.c_str(),
4963 }
4964
4965 if (m_options.m_line_start != 0) {
4966 specifier_up->AddLineSpecification(
4967 m_options.m_line_start,
4969 }
4970
4971 if (m_options.m_line_end != UINT_MAX) {
4972 specifier_up->AddLineSpecification(
4974 }
4975
4976 if (!m_options.m_function_name.empty()) {
4977 specifier_up->AddSpecification(
4978 m_options.m_function_name.c_str(),
4980 }
4981 }
4982
4983 if (specifier_up)
4984 new_hook_sp->SetSpecifier(specifier_up.release());
4985
4986 // Should we run at the initial stop:
4987 new_hook_sp->SetRunAtInitialStop(m_options.m_at_initial_stop);
4988
4989 // Next see if any of the thread options have been entered:
4990
4991 if (m_options.m_thread_specified) {
4992 ThreadSpec *thread_spec = new ThreadSpec();
4993
4994 if (m_options.m_thread_id != LLDB_INVALID_THREAD_ID) {
4995 thread_spec->SetTID(m_options.m_thread_id);
4996 }
4997
4998 if (m_options.m_thread_index != UINT32_MAX)
4999 thread_spec->SetIndex(m_options.m_thread_index);
5000
5001 if (!m_options.m_thread_name.empty())
5002 thread_spec->SetName(m_options.m_thread_name.c_str());
5004 if (!m_options.m_queue_name.empty())
5005 thread_spec->SetQueueName(m_options.m_queue_name.c_str());
5006
5007 new_hook_sp->SetThreadSpecifier(thread_spec);
5008 }
5009
5010 new_hook_sp->SetAutoContinue(m_options.m_auto_continue);
5012 // This is a command line stop hook:
5013 Target::StopHookCommandLine *hook_ptr =
5014 static_cast<Target::StopHookCommandLine *>(new_hook_sp.get());
5016 result.AppendMessageWithFormatv("Stop hook #{0} added.",
5017 new_hook_sp->GetID());
5018 } else if (!m_python_class_options.GetName().empty()) {
5019 // This is a scripted stop hook:
5020 Target::StopHookScripted *hook_ptr =
5021 static_cast<Target::StopHookScripted *>(new_hook_sp.get());
5022 ScriptedMetadata scripted_metadata(
5023 m_python_class_options.GetName(),
5024 m_python_class_options.GetStructuredData());
5025 Status error = hook_ptr->SetScriptCallback(scripted_metadata);
5026 if (error.Success())
5027 result.AppendMessageWithFormatv("Stop hook #{0} added.",
5028 new_hook_sp->GetID());
5029 else {
5030 // FIXME: Set the stop hook ID counter back.
5031 result.AppendErrorWithFormat("Couldn't add stop hook: %s",
5032 error.AsCString());
5033 target->UndoCreateStopHook(new_hook_sp->GetID());
5034 return;
5035 }
5036 } else {
5037 m_stop_hook_sp = new_hook_sp;
5038 m_interpreter.GetLLDBCommandsFromIOHandler("> ", // Prompt
5039 *this); // IOHandlerDelegate
5040 }
5042 }
5043
5044private:
5046 OptionGroupPythonClassWithDict m_python_class_options;
5047 OptionGroupOptions m_all_options;
5048
5050};
5051
5052#pragma mark CommandObjectTargetStopHookDelete
5053
5054// CommandObjectTargetStopHookDelete
5055
5057public:
5060 interpreter, "target stop-hook delete", "Delete a stop-hook.",
5061 "target stop-hook delete [<idx>]", eCommandAllowsDummyTarget) {
5063 R"(
5064Deletes the stop hook by index.
5065
5066At any given stop, all enabled stop hooks that pass the stop filter will
5067get a chance to run. That means if one stop-hook deletes another stop hook
5068while executing, the deleted stop hook will still fire for the stop at which
5069it was deleted.
5070 )");
5072 }
5073
5074 ~CommandObjectTargetStopHookDelete() override = default;
5075
5076 void
5078 OptionElementVector &opt_element_vector) override {
5079 if (request.GetCursorIndex())
5080 return;
5081 CommandObject::HandleArgumentCompletion(request, opt_element_vector);
5082 }
5083
5084protected:
5085 void DoExecute(Args &command, CommandReturnObject &result) override {
5086 Target *target = GetTarget();
5087 assert(target && "target guaranteed by eCommandRequiresTarget");
5088 // FIXME: see if we can use the breakpoint id style parser?
5089 size_t num_args = command.GetArgumentCount();
5090 if (num_args == 0) {
5091 if (!m_interpreter.Confirm("Delete all stop hooks?", true)) {
5093 return;
5094 } else {
5095 target->RemoveAllStopHooks();
5096 }
5097 } else {
5098 for (size_t i = 0; i < num_args; i++) {
5099 lldb::user_id_t user_id;
5100 if (!llvm::to_integer(command.GetArgumentAtIndex(i), user_id)) {
5101 result.AppendErrorWithFormat("invalid stop hook id: \"%s\"",
5102 command.GetArgumentAtIndex(i));
5103 return;
5104 }
5105 if (!target->RemoveStopHookByID(user_id)) {
5106 result.AppendErrorWithFormat("unknown stop hook id: \"%s\"",
5107 command.GetArgumentAtIndex(i));
5108 return;
5109 }
5110 }
5111 }
5113 }
5114};
5115
5116#pragma mark CommandObjectTargetStopHookEnableDisable
5117
5118// CommandObjectTargetStopHookEnableDisable
5119
5121public:
5123 bool enable, const char *name,
5124 const char *help, const char *syntax)
5125 : CommandObjectParsed(interpreter, name, help, syntax,
5126 eCommandAllowsDummyTarget),
5127 m_enable(enable) {
5129 }
5130
5132
5133 void
5135 OptionElementVector &opt_element_vector) override {
5136 if (request.GetCursorIndex())
5137 return;
5138 CommandObject::HandleArgumentCompletion(request, opt_element_vector);
5139 }
5140
5141protected:
5142 void DoExecute(Args &command, CommandReturnObject &result) override {
5143 Target *target = GetTarget();
5144 assert(target && "target guaranteed by eCommandRequiresTarget");
5145 // FIXME: see if we can use the breakpoint id style parser?
5146 size_t num_args = command.GetArgumentCount();
5147 bool success;
5148
5149 if (num_args == 0) {
5151 } else {
5152 for (size_t i = 0; i < num_args; i++) {
5153 lldb::user_id_t user_id;
5154 if (!llvm::to_integer(command.GetArgumentAtIndex(i), user_id)) {
5155 result.AppendErrorWithFormat("invalid stop hook id: \"%s\"",
5156 command.GetArgumentAtIndex(i));
5157 return;
5158 }
5159 success = target->SetStopHookActiveStateByID(user_id, m_enable);
5160 if (!success) {
5161 result.AppendErrorWithFormat("unknown stop hook id: \"%s\"",
5162 command.GetArgumentAtIndex(i));
5163 return;
5164 }
5165 }
5166 }
5168 }
5169
5170private:
5172};
5173
5174#pragma mark CommandObjectTargetStopHookList
5175
5176// CommandObjectTargetStopHookList
5177#define LLDB_OPTIONS_target_stop_hook_list
5178#include "CommandOptions.inc"
5179
5181public:
5183 : CommandObjectParsed(interpreter, "target stop-hook list",
5184 "List all stop-hooks.", nullptr,
5185 eCommandAllowsDummyTarget) {}
5186
5188
5189 Options *GetOptions() override { return &m_options; }
5190
5191 class CommandOptions : public Options {
5192 public:
5193 CommandOptions() = default;
5194 ~CommandOptions() override = default;
5195
5196 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
5197 ExecutionContext *execution_context) override {
5198 Status error;
5199 const int short_option = m_getopt_table[option_idx].val;
5200
5201 switch (short_option) {
5202 case 'i':
5203 m_internal = true;
5204 break;
5205 default:
5206 llvm_unreachable("Unimplemented option");
5207 }
5208
5209 return error;
5210 }
5211
5212 void OptionParsingStarting(ExecutionContext *execution_context) override {
5213 m_internal = false;
5214 }
5215
5216 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
5217 return llvm::ArrayRef(g_target_stop_hook_list_options);
5218 }
5219
5220 // Instance variables to hold the values for command options.
5221 bool m_internal = false;
5222 };
5223
5224protected:
5225 void DoExecute(Args &command, CommandReturnObject &result) override {
5226 Target *target = GetTarget();
5227 assert(target && "target guaranteed by eCommandRequiresTarget");
5228 bool printed_hook = false;
5229 for (auto &hook : target->GetStopHooks(m_options.m_internal)) {
5230 if (printed_hook)
5231 result.GetOutputStream().PutCString("\n");
5232 hook->GetDescription(result.GetOutputStream(), eDescriptionLevelFull);
5233 printed_hook = true;
5234 }
5235
5236 if (!printed_hook)
5237 result.GetOutputStream().PutCString("No stop hooks.\n");
5238
5240 }
5241
5242private:
5244};
5245
5246#pragma mark CommandObjectMultiwordTargetStopHooks
5247
5248// CommandObjectMultiwordTargetStopHooks
5249
5251public:
5254 interpreter, "target stop-hook",
5255 "Commands for operating on debugger target stop-hooks.",
5256 "target stop-hook <subcommand> [<subcommand-options>]") {
5258 new CommandObjectTargetStopHookAdd(interpreter)));
5260 "delete",
5262 LoadSubCommand("disable",
5264 interpreter, false, "target stop-hook disable [<id>]",
5265 "Disable a stop-hook.", "target stop-hook disable")));
5266 LoadSubCommand("enable",
5268 interpreter, true, "target stop-hook enable [<id>]",
5269 "Enable a stop-hook.", "target stop-hook enable")));
5271 interpreter)));
5272 }
5273
5275};
5276
5277#pragma mark CommandObjectTargetHookAdd
5278
5279#define LLDB_OPTIONS_target_hook_add
5280#include "CommandOptions.inc"
5281
5284public:
5286 public:
5287 CommandOptions() = default;
5288 ~CommandOptions() override = default;
5289
5290 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
5291 return llvm::ArrayRef(g_target_hook_add_options);
5292 }
5293
5294 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
5295 ExecutionContext *execution_context) override {
5296 Status error;
5297 const int short_option =
5298 g_target_hook_add_options[option_idx].short_option;
5299 switch (short_option) {
5300 case 'o':
5301 m_use_one_liner = true;
5302 m_one_liner.push_back(std::string(option_arg));
5303 break;
5304 case 'L':
5305 m_on_load = true;
5306 break;
5307 case 'u':
5308 m_on_unload = true;
5309 break;
5310 case 'S':
5311 m_on_stop = true;
5312 break;
5313 case 's':
5314 m_module_name = std::string(option_arg);
5315 m_sym_ctx_specified = true;
5316 break;
5317 case 'x': {
5318 uint32_t thread_index;
5319 if (option_arg.getAsInteger(0, thread_index))
5320 error = Status::FromErrorStringWithFormat("invalid thread index '%s'",
5321 option_arg.str().c_str());
5322 else
5323 m_thread_index = thread_index;
5324 m_thread_specified = true;
5325 break;
5326 }
5327 case 't': {
5328 lldb::tid_t thread_id;
5329 if (option_arg.getAsInteger(0, thread_id))
5330 error = Status::FromErrorStringWithFormat("invalid thread id '%s'",
5331 option_arg.str().c_str());
5332 else
5333 m_thread_id = thread_id;
5334 m_thread_specified = true;
5335 break;
5336 }
5337 case 'T':
5338 m_thread_name = std::string(option_arg);
5339 m_thread_specified = true;
5340 break;
5341 case 'q':
5342 m_queue_name = std::string(option_arg);
5343 m_thread_specified = true;
5344 break;
5345 case 'f':
5346 m_file_name = std::string(option_arg);
5347 m_sym_ctx_specified = true;
5348 break;
5349 case 'l': {
5350 uint32_t line;
5351 if (option_arg.getAsInteger(0, line))
5353 "invalid start line number '%s'", option_arg.str().c_str());
5354 else
5355 m_line_start = line;
5356 m_sym_ctx_specified = true;
5357 break;
5358 }
5359 case 'e': {
5360 uint32_t line;
5361 if (option_arg.getAsInteger(0, line))
5363 "invalid end line number '%s'", option_arg.str().c_str());
5364 else
5365 m_line_end = line;
5366 m_sym_ctx_specified = true;
5367 break;
5368 }
5369 case 'c':
5370 m_class_name = std::string(option_arg);
5371 m_sym_ctx_specified = true;
5372 break;
5373 case 'n':
5374 m_function_name = std::string(option_arg);
5375 m_sym_ctx_specified = true;
5376 break;
5377 case 'G': {
5378 bool value, success;
5379 value = OptionArgParser::ToBoolean(option_arg, false, &success);
5380 if (success)
5381 m_auto_continue = value;
5382 else
5384 "invalid boolean value '%s' passed for -G option",
5385 option_arg.str().c_str());
5386 break;
5387 }
5388 case 'I': {
5389 bool value, success;
5390 value = OptionArgParser::ToBoolean(option_arg, true, &success);
5391 if (success)
5392 m_at_initial_stop = value;
5393 else
5395 "invalid boolean value '%s' passed for -I option",
5396 option_arg.str().c_str());
5397 break;
5398 }
5399 default:
5400 llvm_unreachable("unhandled option");
5401 }
5402 return error;
5403 }
5404
5405 void OptionParsingStarting(ExecutionContext *execution_context) override {
5406 m_use_one_liner = false;
5407 m_one_liner.clear();
5408 m_on_load = false;
5409 m_on_unload = false;
5410 m_on_stop = false;
5411 m_sym_ctx_specified = false;
5412 m_thread_specified = false;
5413 m_module_name.clear();
5414 m_file_name.clear();
5415 m_class_name.clear();
5416 m_function_name.clear();
5417 m_line_start = 0;
5418 m_line_end = UINT_MAX;
5421 m_thread_name.clear();
5422 m_queue_name.clear();
5423 m_auto_continue = false;
5424 m_at_initial_stop = true;
5425 }
5426
5427 std::vector<std::string> m_one_liner;
5428 bool m_use_one_liner = false;
5429 bool m_on_load = false;
5430 bool m_on_unload = false;
5431 bool m_on_stop = false;
5432
5433 // Filter options (for stop trigger).
5436 std::string m_module_name;
5437 std::string m_file_name;
5438 std::string m_class_name;
5439 std::string m_function_name;
5440 uint32_t m_line_start = 0;
5441 uint32_t m_line_end = UINT_MAX;
5444 std::string m_thread_name;
5445 std::string m_queue_name;
5446 bool m_auto_continue = false;
5448 };
5449
5452 interpreter, "target hook add",
5453 "Add a hook to be executed on target lifecycle events.",
5454 "target hook add", eCommandAllowsDummyTarget),
5457 m_python_class_options("scripted hook", false, 'P') {
5458 SetHelpLong(R"help(
5459Command-based hooks:
5460--------------------
5461 Specify which triggers the hook responds to with --on-load (-L),
5462 --on-unload (-u), and/or --on-stop (-S). At least one trigger is required.
5463 Provide commands with --one-liner (-o), or omit -o to enter an interactive
5464 command editor. All commands run for every trigger the hook is signed up
5465 for; there is no per-trigger command list.
5466
5467 Examples:
5468 target hook add -L -o "script print('module loaded')"
5469 target hook add -L -u -o "script print('module event')"
5470 target hook add -S -o "bt"
5471 target hook add -L -u -S -o "script print('all events')"
5472 target hook add -S -s mylib.so -n main -o "bt"
5473 target hook add -S -G true -o "thread info"
5475Python class hooks:
5476-------------------
5477 Provide a Python class with --python-class (-P). The class controls which
5478 events it handles by implementing the corresponding methods; you do not
5479 specify triggers on the command line. Use -k <key> -v <value> to pass
5480 extra_args to the class constructor.
5481
5482 Examples:
5483 target hook add -P mymodule.MyHook
5484 target hook add -P mymodule.MyHook -k verbose -v true
5486 The Python class should implement at least one of these methods:
5487
5488 class MyHook:
5489 def __init__(self, target, extra_args, internal_dict):
5490 self.target = target
5491 def handle_module_loaded(self, stream):
5492 pass
5493 def handle_module_unloaded(self, stream):
5494 pass
5495 def handle_stop(self, exe_ctx, stream):
5496 return True # True = should_stop, False = continue
5497
5498Filter options:
5499---------------
5500 Filters (-s, -f, -l, -e, -c, -n, -x, -t, -T, -q) restrict when the hook
5501 fires. They apply to both command-based and Python class hooks.
5502)help");
5503 // Python class options (-P, -k, -v) are placed in Set 2 (dst_mask).
5504 // src_mask must cover Set 1 | Set 2 to match the internal usage masks of
5505 // OptionGroupPythonClassWithDict (class=Set1, key/value=Set2).
5506 // Since -o, -L, -u, -S are Group<1> only, the parser prevents mixing.
5509 m_all_options.Append(&m_options);
5510 m_all_options.Finalize();
5511 }
5513 ~CommandObjectTargetHookAdd() override = default;
5514
5515 Options *GetOptions() override { return &m_all_options; }
5516
5517protected:
5518 void IOHandlerActivated(IOHandler &io_handler, bool interactive) override {
5519 if (interactive) {
5520 if (lldb::LockableStreamFileSP output_sp =
5521 io_handler.GetOutputStreamFileSP()) {
5522 LockedStreamFile locked_stream = output_sp->Lock();
5523 locked_stream.PutCString(
5524 "Enter your hook command(s). Type 'DONE' to end.\n");
5525 }
5526 }
5527 }
5528
5529 void IOHandlerInputComplete(IOHandler &io_handler,
5530 std::string &line) override {
5531 if (m_hook_sp) {
5532 if (line.empty()) {
5533 if (lldb::LockableStreamFileSP error_sp =
5534 io_handler.GetErrorStreamFileSP()) {
5535 LockedStreamFile locked_stream = error_sp->Lock();
5536 locked_stream.Printf("error: hook #%" PRIu64
5537 " aborted, no commands.\n",
5538 m_hook_sp->GetID());
5539 }
5540 GetTarget()->UndoCreateHook(m_hook_sp->GetID());
5541 } else {
5542 auto *hook = static_cast<Target::HookCommandLine *>(m_hook_sp.get());
5543 hook->SetActionFromString(line);
5544 if (lldb::LockableStreamFileSP output_sp =
5545 io_handler.GetOutputStreamFileSP()) {
5546 LockedStreamFile locked_stream = output_sp->Lock();
5547 locked_stream.Printf("Hook #%" PRIu64 " added.\n",
5548 m_hook_sp->GetID());
5549 }
5550 }
5551 m_hook_sp.reset();
5552 }
5553 io_handler.SetIsDone(true);
5554 }
5555
5556 void DoExecute(Args &command, CommandReturnObject &result) override {
5557 m_hook_sp.reset();
5558 Target *target = GetTarget();
5559 assert(target && "target guaranteed by eCommandRequiresTarget");
5560 bool is_python_class = !m_python_class_options.GetName().empty();
5561
5562 // Command-based hooks require at least one explicit trigger.
5563 if (!is_python_class && !m_options.m_on_load && !m_options.m_on_unload &&
5564 !m_options.m_on_stop) {
5565 result.AppendError("at least one trigger must be specified: "
5566 "--on-load (-L), --on-unload (-u), or --on-stop (-S)");
5567 return;
5568 }
5569
5570 Target::Hook::HookKind hook_kind =
5571 is_python_class ? Target::Hook::HookKind::ScriptBased
5572 : Target::Hook::HookKind::CommandBased;
5573
5574 Target::HookSP new_hook_sp = target->CreateHook(hook_kind);
5575
5576 if (!is_python_class) {
5577 // Build trigger mask from explicit command-line flags.
5578 auto *cmd_hook =
5579 static_cast<Target::HookCommandLine *>(new_hook_sp.get());
5580 uint32_t trigger_mask = 0;
5581 if (m_options.m_on_load)
5582 trigger_mask |= Target::Hook::kModulesLoaded;
5583 if (m_options.m_on_unload)
5584 trigger_mask |= Target::Hook::kModulesUnloaded;
5585 if (m_options.m_on_stop)
5586 trigger_mask |= Target::Hook::kProcessStop;
5587 cmd_hook->SetTriggerMask(trigger_mask);
5588 }
5589 // Python class hooks: triggers are computed in SetScriptCallback based
5590 // on which callback methods the class implements.
5591
5592 // Set up symbol context specifier if filter options were provided.
5593 if (m_options.m_sym_ctx_specified) {
5594 auto specifier_up =
5595 std::make_unique<SymbolContextSpecifier>(target->shared_from_this());
5596
5597 if (!m_options.m_module_name.empty())
5598 specifier_up->AddSpecification(
5599 m_options.m_module_name.c_str(),
5601
5602 if (!m_options.m_class_name.empty())
5603 specifier_up->AddSpecification(
5604 m_options.m_class_name.c_str(),
5606
5607 if (!m_options.m_file_name.empty())
5608 specifier_up->AddSpecification(m_options.m_file_name.c_str(),
5610
5611 if (m_options.m_line_start != 0)
5612 specifier_up->AddLineSpecification(
5613 m_options.m_line_start,
5615
5616 if (m_options.m_line_end != UINT_MAX)
5617 specifier_up->AddLineSpecification(
5619
5620 if (!m_options.m_function_name.empty())
5621 specifier_up->AddSpecification(
5622 m_options.m_function_name.c_str(),
5624
5625 new_hook_sp->SetSCSpecifier(specifier_up.release());
5626 }
5627
5628 // Set up thread specifier.
5629 if (m_options.m_thread_specified) {
5630 ThreadSpec *thread_spec = new ThreadSpec();
5631
5632 if (m_options.m_thread_id != LLDB_INVALID_THREAD_ID)
5633 thread_spec->SetTID(m_options.m_thread_id);
5635 if (m_options.m_thread_index != UINT32_MAX)
5636 thread_spec->SetIndex(m_options.m_thread_index);
5638 if (!m_options.m_thread_name.empty())
5639 thread_spec->SetName(m_options.m_thread_name.c_str());
5640
5641 if (!m_options.m_queue_name.empty())
5642 thread_spec->SetQueueName(m_options.m_queue_name.c_str());
5643
5644 new_hook_sp->SetThreadSpecifier(thread_spec);
5645 }
5646
5647 new_hook_sp->SetAutoContinue(m_options.m_auto_continue);
5648 new_hook_sp->SetRunAtInitialStop(m_options.m_at_initial_stop);
5649
5651 auto *hook = static_cast<Target::HookCommandLine *>(new_hook_sp.get());
5653 result.AppendMessageWithFormatv("Hook #{0} added.\n",
5654 new_hook_sp->GetID());
5655 } else if (!m_python_class_options.GetName().empty()) {
5656 auto *hook = static_cast<Target::HookScripted *>(new_hook_sp.get());
5657 ScriptedMetadata scripted_metadata(
5658 m_python_class_options.GetName(),
5659 m_python_class_options.GetStructuredData());
5660 Status callback_error = hook->SetScriptCallback(scripted_metadata);
5661 if (callback_error.Fail()) {
5662 result.AppendErrorWithFormat("couldn't add hook: %s",
5663 callback_error.AsCString());
5664 target->UndoCreateHook(new_hook_sp->GetID());
5665 return;
5666 }
5667 result.AppendMessageWithFormatv("Hook #{0} added.\n",
5668 new_hook_sp->GetID());
5669 } else {
5670 m_hook_sp = new_hook_sp;
5671 m_interpreter.GetLLDBCommandsFromIOHandler("> ", // prompt
5672 *this); // delegate
5673 }
5675 }
5676
5677private:
5679 OptionGroupPythonClassWithDict m_python_class_options;
5680 OptionGroupOptions m_all_options;
5682};
5683
5684#pragma mark CommandObjectTargetHookDelete
5685
5687public:
5689 : CommandObjectParsed(interpreter, "target hook delete", "Delete a hook.",
5690 "target hook delete [<id>]",
5691 eCommandAllowsDummyTarget) {
5693 }
5694
5696
5697protected:
5698 void DoExecute(Args &command, CommandReturnObject &result) override {
5699 Target *target = GetTarget();
5700 assert(target && "target guaranteed by eCommandRequiresTarget");
5701 if (command.GetArgumentCount() == 0) {
5702 if (!m_interpreter.Confirm("Delete all hooks?", true)) {
5704 return;
5705 }
5706 target->RemoveAllHooks();
5708 return;
5709 }
5710
5711 for (size_t i = 0; i < command.GetArgumentCount(); i++) {
5712 lldb::user_id_t user_id;
5713 if (!llvm::to_integer(command.GetArgumentAtIndex(i), user_id)) {
5714 result.AppendErrorWithFormat("invalid hook id: \"%s\"",
5715 command.GetArgumentAtIndex(i));
5716 return;
5717 }
5718 if (!target->RemoveHookByID(user_id)) {
5719 result.AppendErrorWithFormat("unknown hook id: \"%s\"",
5720 command.GetArgumentAtIndex(i));
5721 return;
5722 }
5723 }
5725 }
5726};
5727
5728#pragma mark CommandObjectTargetHookEnableDisable
5729
5731public:
5733 bool enable, const char *name,
5734 const char *help, const char *syntax)
5735 : CommandObjectParsed(interpreter, name, help, syntax,
5736 eCommandAllowsDummyTarget),
5737 m_enable(enable) {
5739 }
5740
5742
5743protected:
5744 void DoExecute(Args &command, CommandReturnObject &result) override {
5745 Target *target = GetTarget();
5746 assert(target && "target guaranteed by eCommandRequiresTarget");
5747 // No IDs = apply to all hooks.
5748 if (command.GetArgumentCount() == 0) {
5751 return;
5752 }
5753
5754 for (size_t i = 0; i < command.GetArgumentCount(); i++) {
5755 lldb::user_id_t user_id;
5756 if (!llvm::to_integer(command.GetArgumentAtIndex(i), user_id)) {
5757 result.AppendErrorWithFormat("invalid hook id: \"%s\"",
5758 command.GetArgumentAtIndex(i));
5759 return;
5760 }
5761 if (!target->SetHookEnabledStateByID(user_id, m_enable)) {
5762 result.AppendErrorWithFormat("unknown hook id: \"%s\"",
5763 command.GetArgumentAtIndex(i));
5764 return;
5765 }
5766 }
5768 }
5769
5770private:
5772};
5773
5774#pragma mark CommandObjectTargetHookModify
5775
5776#define LLDB_OPTIONS_target_hook_modify
5777#include "CommandOptions.inc"
5778
5779/// Modify trigger settings on a hook. Only valid for command-based hooks;
5780/// scripted hooks derive their triggers from the class methods.
5782public:
5783 class CommandOptions : public Options {
5784 public:
5785 CommandOptions() = default;
5786 ~CommandOptions() override = default;
5787
5788 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
5789 return llvm::ArrayRef(g_target_hook_modify_options);
5790 }
5791
5792 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
5793 ExecutionContext *execution_context) override {
5794 Status error;
5795 const int short_option =
5796 g_target_hook_modify_options[option_idx].short_option;
5797 switch (short_option) {
5798 case 'e':
5799 m_enable_trigger = option_arg.str();
5800 break;
5801 case 'd':
5802 m_disable_trigger = option_arg.str();
5803 break;
5804 default:
5805 llvm_unreachable("unhandled option");
5806 }
5807 return error;
5808 }
5809
5810 void OptionParsingStarting(ExecutionContext *execution_context) override {
5811 m_enable_trigger.clear();
5812 m_disable_trigger.clear();
5813 }
5814
5815 std::string m_enable_trigger;
5817 };
5818
5820 : CommandObjectParsed(interpreter, "target hook modify",
5821 "Modify trigger settings on a hook.",
5822 "target hook modify [--enable-trigger <name>] "
5823 "[--disable-trigger <name>] [<id>]",
5824 eCommandAllowsDummyTarget) {
5826 SetHelpLong(R"help(
5827Modify trigger settings on command-based hooks. Scripted hooks derive their
5828triggers from the class methods and cannot be modified.
5830If no hook ID is given, the last added hook is modified.
5832Valid trigger names: load, unload, stop.
5833
5834Examples:
5835 target hook modify --enable-trigger stop 1
5836 target hook modify --disable-trigger load 1
5837 target hook modify --enable-trigger stop (modifies last added hook)
5838)help");
5839 }
5840
5841 ~CommandObjectTargetHookModify() override = default;
5842
5843 Options *GetOptions() override { return &m_options; }
5845protected:
5846 static uint32_t ParseTriggerName(llvm::StringRef name) {
5847 if (name == "load")
5849 if (name == "unload")
5851 if (name == "stop")
5853 return 0;
5854 }
5855
5856 void DoExecute(Args &command, CommandReturnObject &result) override {
5857 Target *target = GetTarget();
5858 assert(target && "target guaranteed by eCommandRequiresTarget");
5859 if (m_options.m_enable_trigger.empty() &&
5860 m_options.m_disable_trigger.empty()) {
5861 result.AppendError("at least one of --enable-trigger or "
5862 "--disable-trigger must be specified");
5863 return;
5864 }
5865
5866 // Resolve the hook ID. Default to last added if not specified.
5867 Target::HookSP hook_sp;
5868 if (command.GetArgumentCount() == 0) {
5869 size_t num_hooks = target->GetNumHooks();
5870 if (num_hooks == 0) {
5871 result.AppendError("no hooks exist");
5872 return;
5873 }
5874 hook_sp = target->GetHookAtIndex(num_hooks - 1);
5875 } else {
5876 lldb::user_id_t user_id;
5877 if (!llvm::to_integer(command.GetArgumentAtIndex(0), user_id)) {
5878 result.AppendErrorWithFormat("invalid hook id: \"%s\"",
5879 command.GetArgumentAtIndex(0));
5880 return;
5881 }
5882 hook_sp = target->GetHookByID(user_id);
5883 if (!hook_sp) {
5884 result.AppendErrorWithFormat("unknown hook id: \"%s\"",
5885 command.GetArgumentAtIndex(0));
5886 return;
5887 }
5888 }
5889
5890 // Reject trigger modification on scripted hooks.
5891 if (hook_sp->GetHookKind() != Target::Hook::HookKind::CommandBased) {
5892 result.AppendError("cannot modify triggers on a scripted hook; "
5893 "triggers are determined by the class methods");
5894 return;
5895 }
5896 auto *cmd_hook = static_cast<Target::HookCommandLine *>(hook_sp.get());
5897
5898 if (!m_options.m_enable_trigger.empty()) {
5899 uint32_t trigger = ParseTriggerName(m_options.m_enable_trigger);
5900 if (!trigger) {
5901 result.AppendErrorWithFormat("unknown trigger name: \"%s\". "
5902 "Valid names: load, unload, stop",
5903 m_options.m_enable_trigger.c_str());
5904 return;
5905 }
5906 cmd_hook->AddTrigger(trigger);
5907 }
5908
5909 if (!m_options.m_disable_trigger.empty()) {
5910 uint32_t trigger = ParseTriggerName(m_options.m_disable_trigger);
5911 if (!trigger) {
5912 result.AppendErrorWithFormat("unknown trigger name: \"%s\". "
5913 "Valid names: load, unload, stop",
5914 m_options.m_disable_trigger.c_str());
5915 return;
5916 }
5917 cmd_hook->RemoveTrigger(trigger);
5918 }
5919
5921 }
5922
5923private:
5925};
5926
5927#pragma mark CommandObjectTargetHookList
5928
5930public:
5932 : CommandObjectParsed(interpreter, "target hook list", "List all hooks.",
5933 "target hook list", eCommandAllowsDummyTarget) {}
5934
5935 ~CommandObjectTargetHookList() override = default;
5936
5937protected:
5938 void DoExecute(Args &command, CommandReturnObject &result) override {
5939 Target *target = GetTarget();
5940 assert(target && "target guaranteed by eCommandRequiresTarget");
5941 size_t num_hooks = target->GetNumHooks();
5942 if (num_hooks == 0) {
5943 result.GetOutputStream().PutCString("No hooks.\n");
5944 } else {
5945 for (size_t i = 0; i < num_hooks; i++) {
5946 Target::HookSP hook_sp = target->GetHookAtIndex(i);
5947 if (hook_sp)
5948 hook_sp->GetDescription(result.GetOutputStream(),
5950 }
5951 }
5953 }
5954};
5955
5956#pragma mark CommandObjectMultiwordTargetHooks
5957
5959public:
5962 interpreter, "target hook",
5963 "Commands for operating on target hooks.",
5964 "target hook <subcommand> [<subcommand-options>]") {
5966 "add", CommandObjectSP(new CommandObjectTargetHookAdd(interpreter)));
5968 interpreter)));
5969 LoadSubCommand("disable",
5971 interpreter, false, "target hook disable",
5972 "Disable a hook.", "target hook disable [<id> ...]")));
5973 LoadSubCommand("enable",
5975 interpreter, true, "target hook enable",
5976 "Enable a hook.", "target hook enable [<id> ...]")));
5978 "list", CommandObjectSP(new CommandObjectTargetHookList(interpreter)));
5980 interpreter)));
5981 }
5982
5984};
5985
5986#pragma mark CommandObjectTargetDumpTypesystem
5987
5988/// Dumps the TypeSystem of the selected Target.
5990public:
5993 interpreter, "target dump typesystem",
5994 "Dump the state of the target's internal type system. Intended to "
5995 "be used for debugging LLDB itself.",
5996 nullptr, eCommandRequiresTarget) {}
5997
5999
6000protected:
6001 void DoExecute(Args &command, CommandReturnObject &result) override {
6002 // Go over every scratch TypeSystem and dump to the command output.
6003 for (lldb::TypeSystemSP ts : GetTarget()->GetScratchTypeSystems())
6004 if (ts)
6005 ts->Dump(result.GetOutputStream().AsRawOstream(), "",
6006 GetCommandInterpreter().GetDebugger().GetUseColor());
6007
6009 }
6010};
6011
6012#pragma mark CommandObjectTargetDumpSectionLoadList
6013
6014/// Dumps the SectionLoadList of the selected Target.
6016public:
6019 interpreter, "target dump section-load-list",
6020 "Dump the state of the target's internal section load list. "
6021 "Intended to be used for debugging LLDB itself.",
6022 nullptr, eCommandRequiresTarget) {}
6023
6025
6026protected:
6027 void DoExecute(Args &command, CommandReturnObject &result) override {
6028 Target *target = GetTarget();
6029 assert(target && "target guaranteed by eCommandRequiresTarget");
6030 target->DumpSectionLoadList(result.GetOutputStream());
6032 }
6033};
6034
6035#pragma mark CommandObjectTargetDump
6036
6037/// Multi-word command for 'target dump'.
6039public:
6040 // Constructors and Destructors
6043 interpreter, "target dump",
6044 "Commands for dumping information about the target.",
6045 "target dump [typesystem|section-load-list]") {
6047 "typesystem",
6049 LoadSubCommand("section-load-list",
6051 interpreter)));
6052 }
6053
6054 ~CommandObjectTargetDump() override = default;
6055};
6056
6057#pragma mark CommandObjectTargetFrameProvider
6058
6059#define LLDB_OPTIONS_target_frame_provider_register
6060#include "CommandOptions.inc"
6061
6063public:
6066 interpreter, "target frame-provider register",
6067 "Register frame provider for all threads in this target.", nullptr,
6068 eCommandRequiresTarget),
6069
6070 m_class_options("target frame-provider", true, 'C', 'k', 'v', 0) {
6073 m_all_options.Finalize();
6074 }
6075
6077
6078 Options *GetOptions() override { return &m_all_options; }
6079
6080 std::optional<std::string> GetRepeatCommand(Args &current_command_args,
6081 uint32_t index) override {
6082 return std::string("");
6083 }
6084
6085protected:
6086 void DoExecute(Args &command, CommandReturnObject &result) override {
6087 ScriptedMetadataSP metadata_sp = std::make_shared<ScriptedMetadata>(
6088 m_class_options.GetName(), m_class_options.GetStructuredData());
6089
6090 Target *target = m_exe_ctx.GetTargetPtr();
6091
6092 if (!target)
6093 class="code hl_function" href="classlldb__private_1_1CommandObject.html#a8fe108f167b4280f3e9cec952614099e">GetDebugger().GetDummyTarget();
6094
6095 // Create the interface for calling static methods.
6097 GetDebugger()
6100
6101 // Create a descriptor from the metadata (applies to all threads by
6102 // default).
6103 ScriptedFrameProviderDescriptor descriptor(metadata_sp);
6104 descriptor.interface_sp = interface_sp;
6105
6106 auto id_or_err = target->AddScriptedFrameProviderDescriptor(descriptor);
6107 if (!id_or_err) {
6108 result.SetError(id_or_err.takeError());
6109 return;
6110 }
6111
6113 "successfully registered scripted frame provider '{0}' for target",
6114 m_class_options.GetName().c_str());
6116 }
6117
6120};
6121
6123public:
6126 interpreter, "target frame-provider clear",
6127 "Clear all registered frame providers from this target.", nullptr,
6128 eCommandRequiresTarget) {}
6129
6131
6132protected:
6133 void DoExecute(Args &command, CommandReturnObject &result) override {
6134 Target *target = m_exe_ctx.GetTargetPtr();
6135 if (!target) {
6136 result.AppendError("invalid target");
6137 return;
6138 }
6139
6141
6143 }
6144};
6145
6147public:
6150 interpreter, "target frame-provider list",
6151 "List all registered frame providers for the target.", nullptr,
6152 eCommandRequiresTarget) {}
6153
6155
6156protected:
6157 void DoExecute(Args &command, CommandReturnObject &result) override {
6158 Target *target = m_exe_ctx.GetTargetPtr();
6159 if (!target)
6160 class="code hl_function" href="classlldb__private_1_1CommandObject.html#a8fe108f167b4280f3e9cec952614099e">GetDebugger().GetDummyTarget();
6161
6162 const auto &descriptors = target->GetScriptedFrameProviderDescriptors();
6163 if (descriptors.empty()) {
6164 result.AppendMessage("no frame providers registered for this target.");
6166 return;
6167 }
6168
6169 Stream &strm = result.GetOutputStream();
6170 strm << llvm::formatv("{0} frame provider(s) registered:\n\n",
6171 descriptors.size());
6172
6173 for (const auto &entry : descriptors) {
6174 const ScriptedFrameProviderDescriptor &descriptor = entry.second;
6175 descriptor.Dump(&strm);
6176 strm.PutChar('\n');
6177 }
6178
6180 }
6181};
6182
6184public:
6187 interpreter, "target frame-provider remove",
6188 "Remove a registered frame provider from the target by id.",
6189 "target frame-provider remove <provider-id>",
6190 eCommandRequiresTarget) {
6192 }
6193
6195
6196protected:
6197 void DoExecute(Args &command, CommandReturnObject &result) override {
6198 Target *target = m_exe_ctx.GetTargetPtr();
6199 if (!target)
6200 class="code hl_function" href="classlldb__private_1_1CommandObject.html#a8fe108f167b4280f3e9cec952614099e">GetDebugger().GetDummyTarget();
6201
6202 std::vector<uint32_t> removed_provider_ids;
6203 for (size_t i = 0; i < command.GetArgumentCount(); i++) {
6204 uint32_t provider_id = 0;
6205 if (!llvm::to_integer(command[i].ref(), provider_id)) {
6206 result.AppendError("target frame-provider remove requires integer "
6207 "provider id argument");
6208 return;
6209 }
6210
6211 if (!target->RemoveScriptedFrameProviderDescriptor(provider_id)) {
6212 result.AppendErrorWithFormat(
6213 "no frame provider named '%u' found in target", provider_id);
6214 return;
6215 }
6216 removed_provider_ids.push_back(provider_id);
6217 }
6218
6219 if (size_t num_removed_providers = removed_provider_ids.size()) {
6221 "Successfully removed {0} frame-providers.", num_removed_providers);
6223 } else {
6224 result.AppendError("0 frame providers removed.\n");
6225 }
6226 }
6227};
6228
6230public:
6233 interpreter, "target frame-provider",
6234 "Commands for registering and viewing frame providers for the "
6235 "target.",
6236 "target frame-provider [<sub-command-options>] ") {
6237 LoadSubCommand("register",
6239 interpreter)));
6240 LoadSubCommand("clear",
6242 new CommandObjectTargetFrameProviderClear(interpreter)));
6244 "list",
6247 "remove", CommandObjectSP(
6248 new CommandObjectTargetFrameProviderRemove(interpreter)));
6249 }
6250
6252};
6253
6254#pragma mark CommandObjectMultiwordTarget
6255
6256// CommandObjectMultiwordTarget
6257
6259 CommandInterpreter &interpreter)
6260 : CommandObjectMultiword(interpreter, "target",
6261 "Commands for operating on debugger targets.",
6262 "target <subcommand> [<subcommand-options>]") {
6263 LoadSubCommand("create",
6264 CommandObjectSP(new CommandObjectTargetCreate(interpreter)));
6265 LoadSubCommand("delete",
6266 CommandObjectSP(new CommandObjectTargetDelete(interpreter)));
6267 LoadSubCommand("dump",
6268 CommandObjectSP(new CommandObjectTargetDump(interpreter)));
6270 "frame-provider",
6272 LoadSubCommand("list",
6273 CommandObjectSP(new CommandObjectTargetList(interpreter)));
6274 LoadSubCommand("select",
6275 CommandObjectSP(new CommandObjectTargetSelect(interpreter)));
6276 LoadSubCommand("show-launch-environment",
6278 interpreter)));
6280 "stop-hook",
6283 interpreter)));
6284 LoadSubCommand("modules",
6286 LoadSubCommand("symbols",
6288 LoadSubCommand("variable",
6290}
6291
static bool GetSeparateDebugInfoList(StructuredData::Array &list, Module *module, bool errors_only, bool load_all_debug_info)
static uint32_t DumpTargetList(TargetList &target_list, bool show_stopped_process_status, Stream &strm)
static void DumpModuleUUID(Stream &strm, Module *module)
static void DumpModuleSections(CommandInterpreter &interpreter, Stream &strm, Module *module)
static void DumpModuleArchitecture(Stream &strm, Module *module, bool full_triple, uint32_t width)
static bool LookupAddressInModule(CommandInterpreter &interpreter, Stream &strm, Module *module, uint32_t resolve_mask, lldb::addr_t raw_addr, lldb::addr_t offset, bool verbose, bool all_ranges)
static void DumpTargetInfo(uint32_t target_idx, Target *target, const char *prefix_cstr, bool show_stopped_process_status, Stream &strm)
static void DumpDirectory(Stream &strm, const FileSpec *file_spec_ptr, uint32_t width)
static uint32_t LookupSymbolInModule(CommandInterpreter &interpreter, Stream &strm, Module *module, const char *name, bool name_is_regex, bool verbose, bool all_ranges)
static size_t LookupTypeInModule(Target *target, CommandInterpreter &interpreter, Stream &strm, Module *module, const char *name_cstr, bool name_is_regex)
static bool DumpModuleSymbolFile(Stream &strm, Module *module)
static void DumpFullpath(Stream &strm, const FileSpec *file_spec_ptr, uint32_t width)
static void DumpDwoFilesTable(Stream &strm, StructuredData::Array &dwo_listings)
static size_t LookupFunctionInModule(CommandInterpreter &interpreter, Stream &strm, Module *module, const char *name, bool name_is_regex, const ModuleFunctionSearchOptions &options, bool verbose, bool all_ranges)
static size_t LookupTypeHere(Target *target, CommandInterpreter &interpreter, Stream &strm, Module &module, const char *name_cstr, bool name_is_regex)
static uint32_t DumpCompileUnitLineTable(CommandInterpreter &interpreter, Stream &strm, Module *module, const FileSpec &file_spec, lldb::DescriptionLevel desc_level)
static void DumpBasename(Stream &strm, const FileSpec *file_spec_ptr, uint32_t width)
static size_t DumpModuleObjfileHeaders(Stream &strm, ModuleList &module_list)
static uint32_t LookupFileAndLineInModule(CommandInterpreter &interpreter, Stream &strm, Module *module, const FileSpec &file_spec, uint32_t line, bool check_inlines, bool verbose, bool all_ranges)
static void DumpSymbolContextList(ExecutionContextScope *exe_scope, Stream &strm, const SymbolContextList &sc_list, bool verbose, bool all_ranges, std::optional< Stream::HighlightSettings > settings=std::nullopt)
static void DumpOsoFilesTable(Stream &strm, StructuredData::Array &oso_listings)
static size_t FindModulesByName(Target *target, const char *module_name, ModuleList &module_list, bool check_global_list)
static void DumpModuleSymtab(CommandInterpreter &interpreter, Stream &strm, Module *module, SortOrder sort_order, Mangled::NamePreference name_preference)
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:519
#define LLDB_LOGF(log,...)
Definition Log.h:389
#define LLDB_SCOPED_TIMERF(...)
Definition Timer.h:86
CommandObjectMultiwordTargetHooks(CommandInterpreter &interpreter)
~CommandObjectMultiwordTargetHooks() override=default
~CommandObjectMultiwordTargetStopHooks() override=default
CommandObjectMultiwordTargetStopHooks(CommandInterpreter &interpreter)
OptionGroupPlatform m_platform_options
~CommandObjectTargetCreate() override=default
OptionGroupArchitecture m_arch_option
CommandObjectTargetCreate(CommandInterpreter &interpreter)
OptionGroupDependents m_add_dependents
void DoExecute(Args &command, CommandReturnObject &result) override
void DoExecute(Args &args, CommandReturnObject &result) override
CommandObjectTargetDelete(CommandInterpreter &interpreter)
~CommandObjectTargetDelete() override=default
Dumps the SectionLoadList of the selected Target.
void DoExecute(Args &command, CommandReturnObject &result) override
~CommandObjectTargetDumpSectionLoadList() override=default
CommandObjectTargetDumpSectionLoadList(CommandInterpreter &interpreter)
Dumps the TypeSystem of the selected Target.
CommandObjectTargetDumpTypesystem(CommandInterpreter &interpreter)
~CommandObjectTargetDumpTypesystem() override=default
void DoExecute(Args &command, CommandReturnObject &result) override
Multi-word command for 'target dump'.
CommandObjectTargetDump(CommandInterpreter &interpreter)
~CommandObjectTargetDump() override=default
void DoExecute(Args &command, CommandReturnObject &result) override
CommandObjectTargetFrameProviderClear(CommandInterpreter &interpreter)
~CommandObjectTargetFrameProviderClear() override=default
void DoExecute(Args &command, CommandReturnObject &result) override
~CommandObjectTargetFrameProviderList() override=default
CommandObjectTargetFrameProviderList(CommandInterpreter &interpreter)
OptionGroupPythonClassWithDict m_class_options
~CommandObjectTargetFrameProviderRegister() override=default
CommandObjectTargetFrameProviderRegister(CommandInterpreter &interpreter)
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 &command, CommandReturnObject &result) override
~CommandObjectTargetFrameProviderRemove() override=default
void DoExecute(Args &command, CommandReturnObject &result) override
CommandObjectTargetFrameProviderRemove(CommandInterpreter &interpreter)
~CommandObjectTargetFrameProvider() override=default
CommandObjectTargetFrameProvider(CommandInterpreter &interpreter)
Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, ExecutionContext *execution_context) override
llvm::ArrayRef< OptionDefinition > GetDefinitions() override
void OptionParsingStarting(ExecutionContext *execution_context) override
CommandObjectTargetHookAdd(CommandInterpreter &interpreter)
void DoExecute(Args &command, CommandReturnObject &result) override
OptionGroupPythonClassWithDict m_python_class_options
void IOHandlerInputComplete(IOHandler &io_handler, std::string &line) override
Called when a line or lines have been retrieved.
~CommandObjectTargetHookAdd() override=default
void IOHandlerActivated(IOHandler &io_handler, bool interactive) override
CommandObjectTargetHookDelete(CommandInterpreter &interpreter)
~CommandObjectTargetHookDelete() override=default
void DoExecute(Args &command, CommandReturnObject &result) override
~CommandObjectTargetHookEnableDisable() override=default
CommandObjectTargetHookEnableDisable(CommandInterpreter &interpreter, bool enable, const char *name, const char *help, const char *syntax)
void DoExecute(Args &command, CommandReturnObject &result) override
CommandObjectTargetHookList(CommandInterpreter &interpreter)
void DoExecute(Args &command, CommandReturnObject &result) override
~CommandObjectTargetHookList() override=default
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
Modify trigger settings on a hook.
void DoExecute(Args &command, CommandReturnObject &result) override
static uint32_t ParseTriggerName(llvm::StringRef name)
CommandObjectTargetHookModify(CommandInterpreter &interpreter)
~CommandObjectTargetHookModify() override=default
CommandObjectTargetList(CommandInterpreter &interpreter)
void DoExecute(Args &args, CommandReturnObject &result) override
~CommandObjectTargetList() override=default
CommandObjectTargetModulesAdd(CommandInterpreter &interpreter)
void DoExecute(Args &args, CommandReturnObject &result) override
~CommandObjectTargetModulesAdd() override=default
CommandObjectTargetModulesDumpClangAST(CommandInterpreter &interpreter)
void DoExecute(Args &command, CommandReturnObject &result) override
~CommandObjectTargetModulesDumpClangAST() override=default
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
~CommandObjectTargetModulesDumpLineTable() override=default
void DoExecute(Args &command, CommandReturnObject &result) override
CommandObjectTargetModulesDumpLineTable(CommandInterpreter &interpreter)
void DoExecute(Args &command, CommandReturnObject &result) override
~CommandObjectTargetModulesDumpObjfile() override=default
CommandObjectTargetModulesDumpObjfile(CommandInterpreter &interpreter)
CommandObjectTargetModulesDumpSections(CommandInterpreter &interpreter)
~CommandObjectTargetModulesDumpSections() override=default
void DoExecute(Args &command, CommandReturnObject &result) 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.
~CommandObjectTargetModulesDumpSeparateDebugInfoFiles() override=default
CommandObjectTargetModulesDumpSeparateDebugInfoFiles(CommandInterpreter &interpreter)
void DoExecute(Args &command, CommandReturnObject &result) override
CommandObjectTargetModulesDumpSymfile(CommandInterpreter &interpreter)
~CommandObjectTargetModulesDumpSymfile() override=default
void DoExecute(Args &command, CommandReturnObject &result) 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.
llvm::ArrayRef< OptionDefinition > GetDefinitions() override
void DoExecute(Args &command, CommandReturnObject &result) override
CommandObjectTargetModulesDumpSymtab(CommandInterpreter &interpreter)
~CommandObjectTargetModulesDumpSymtab() override=default
~CommandObjectTargetModulesDump() override=default
CommandObjectTargetModulesDump(CommandInterpreter &interpreter)
CommandObjectTargetModulesImageSearchPaths(CommandInterpreter &interpreter)
~CommandObjectTargetModulesImageSearchPaths() override=default
llvm::ArrayRef< OptionDefinition > GetDefinitions() override
void OptionParsingStarting(ExecutionContext *execution_context) override
std::vector< std::pair< char, uint32_t > > FormatWidthCollection
Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, ExecutionContext *execution_context) override
Set the value of an option.
CommandObjectTargetModulesList(CommandInterpreter &interpreter)
~CommandObjectTargetModulesList() override=default
void DoExecute(Args &command, CommandReturnObject &result) override
void PrintModule(Target &target, Module *module, int indent, Stream &strm)
void DoExecute(Args &args, CommandReturnObject &result) override
~CommandObjectTargetModulesLoad() override=default
CommandObjectTargetModulesLoad(CommandInterpreter &interpreter)
void OptionParsingStarting(ExecutionContext *execution_context) override
Status OptionParsingFinished(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
bool LookupInModule(CommandInterpreter &interpreter, Module *module, CommandReturnObject &result, bool &syntax_error)
~CommandObjectTargetModulesLookup() override=default
void DoExecute(Args &command, CommandReturnObject &result) override
bool LookupHere(CommandInterpreter &interpreter, CommandReturnObject &result, bool &syntax_error)
CommandObjectTargetModulesLookup(CommandInterpreter &interpreter)
CommandObjectTargetModulesModuleAutoComplete(CommandInterpreter &interpreter, const char *name, const char *help, const char *syntax, uint32_t flags=0)
~CommandObjectTargetModulesModuleAutoComplete() override=default
void HandleArgumentCompletion(CompletionRequest &request, OptionElementVector &opt_element_vector) override
The default version handles argument definitions that have only one argument type,...
~CommandObjectTargetModulesSearchPathsAdd() override=default
void DoExecute(Args &command, CommandReturnObject &result) override
CommandObjectTargetModulesSearchPathsAdd(CommandInterpreter &interpreter)
void DoExecute(Args &command, CommandReturnObject &result) override
~CommandObjectTargetModulesSearchPathsClear() override=default
CommandObjectTargetModulesSearchPathsClear(CommandInterpreter &interpreter)
void HandleArgumentCompletion(CompletionRequest &request, OptionElementVector &opt_element_vector) override
The default version handles argument definitions that have only one argument type,...
~CommandObjectTargetModulesSearchPathsInsert() override=default
CommandObjectTargetModulesSearchPathsInsert(CommandInterpreter &interpreter)
void DoExecute(Args &command, CommandReturnObject &result) override
~CommandObjectTargetModulesSearchPathsList() override=default
CommandObjectTargetModulesSearchPathsList(CommandInterpreter &interpreter)
void DoExecute(Args &command, CommandReturnObject &result) override
~CommandObjectTargetModulesSearchPathsQuery() override=default
void DoExecute(Args &command, CommandReturnObject &result) override
CommandObjectTargetModulesSearchPathsQuery(CommandInterpreter &interpreter)
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
CommandObjectTargetModulesShowUnwind(CommandInterpreter &interpreter)
void DoExecute(Args &command, CommandReturnObject &result) override
~CommandObjectTargetModulesShowUnwind() override=default
CommandObjectTargetModulesSourceFileAutoComplete(CommandInterpreter &interpreter, const char *name, const char *help, const char *syntax, uint32_t flags)
void HandleArgumentCompletion(CompletionRequest &request, OptionElementVector &opt_element_vector) override
The default version handles argument definitions that have only one argument type,...
~CommandObjectTargetModulesSourceFileAutoComplete() override=default
~CommandObjectTargetModules() override=default
const CommandObjectTargetModules & operator=(const CommandObjectTargetModules &)=delete
CommandObjectTargetModules(const CommandObjectTargetModules &)=delete
CommandObjectTargetModules(CommandInterpreter &interpreter)
~CommandObjectTargetSelect() override=default
void DoExecute(Args &args, CommandReturnObject &result) override
CommandObjectTargetSelect(CommandInterpreter &interpreter)
CommandObjectTargetShowLaunchEnvironment(CommandInterpreter &interpreter)
void DoExecute(Args &args, CommandReturnObject &result) override
~CommandObjectTargetShowLaunchEnvironment() override=default
Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, ExecutionContext *execution_context) override
llvm::ArrayRef< OptionDefinition > GetDefinitions() override
void OptionParsingStarting(ExecutionContext *execution_context) override
void IOHandlerActivated(IOHandler &io_handler, bool interactive) override
CommandObjectTargetStopHookAdd(CommandInterpreter &interpreter)
void IOHandlerInputComplete(IOHandler &io_handler, std::string &line) override
Called when a line or lines have been retrieved.
~CommandObjectTargetStopHookAdd() override=default
OptionGroupPythonClassWithDict m_python_class_options
void DoExecute(Args &command, CommandReturnObject &result) 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,...
CommandObjectTargetStopHookDelete(CommandInterpreter &interpreter)
~CommandObjectTargetStopHookDelete() override=default
~CommandObjectTargetStopHookEnableDisable() override=default
void HandleArgumentCompletion(CompletionRequest &request, OptionElementVector &opt_element_vector) override
The default version handles argument definitions that have only one argument type,...
void DoExecute(Args &command, CommandReturnObject &result) override
CommandObjectTargetStopHookEnableDisable(CommandInterpreter &interpreter, bool enable, const char *name, const char *help, const char *syntax)
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
void DoExecute(Args &command, CommandReturnObject &result) override
~CommandObjectTargetStopHookList() override=default
CommandObjectTargetStopHookList(CommandInterpreter &interpreter)
bool AddSymbolsForUUID(CommandReturnObject &result, bool &flush)
bool DownloadObjectAndSymbolFile(ModuleSpec &module_spec, CommandReturnObject &result, bool &flush)
bool AddSymbolsForStack(CommandReturnObject &result, bool &flush)
CommandObjectTargetSymbolsAdd(CommandInterpreter &interpreter)
bool AddSymbolsForFrame(CommandReturnObject &result, bool &flush)
~CommandObjectTargetSymbolsAdd() override=default
void DoExecute(Args &args, CommandReturnObject &result) override
bool AddModuleSymbols(Target *target, ModuleSpec &module_spec, bool &flush, CommandReturnObject &result)
bool AddSymbolsForFile(CommandReturnObject &result, bool &flush)
const CommandObjectTargetSymbols & operator=(const CommandObjectTargetSymbols &)=delete
CommandObjectTargetSymbols(CommandInterpreter &interpreter)
~CommandObjectTargetSymbols() override=default
CommandObjectTargetSymbols(const CommandObjectTargetSymbols &)=delete
void DumpGlobalVariableList(const ExecutionContext &exe_ctx, const SymbolContext &sc, const VariableList &variable_list, CommandReturnObject &result)
void DumpValueObject(Stream &s, VariableSP &var_sp, ValueObjectSP &valobj_sp, const char *root_name)
static size_t GetVariableCallback(void *baton, const char *name, VariableList &variable_list)
static const uint32_t SHORT_OPTION_SHLB
CommandObjectTargetVariable(CommandInterpreter &interpreter)
OptionGroupFileList m_option_shared_libraries
void DoExecute(Args &args, CommandReturnObject &result) override
OptionGroupFileList m_option_compile_units
static const uint32_t SHORT_OPTION_FILE
OptionGroupValueObjectDisplay m_varobj_options
~CommandObjectTargetVariable() override=default
~OptionGroupDependents() override=default
OptionGroupDependents()=default
LoadDependentFiles m_load_dependent_files
OptionGroupDependents(const OptionGroupDependents &)=delete
const OptionGroupDependents & operator=(const OptionGroupDependents &)=delete
void OptionParsingStarting(ExecutionContext *execution_context) override
Status SetOptionValue(uint32_t, const char *, ExecutionContext *)=delete
Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value, ExecutionContext *execution_context) override
llvm::ArrayRef< OptionDefinition > GetDefinitions() override
virtual lldb::addr_t FixCodeAddress(lldb::addr_t pc)
Some targets might use bits in a code address to indicate a mode switch.
Definition ABI.cpp:141
A section + offset based address class.
Definition Address.h:62
lldb::addr_t GetLoadAddress(Target *target) const
Get the load address.
Definition Address.cpp:303
bool SetLoadAddress(lldb::addr_t load_addr, Target *target, bool allow_section_end=false)
Set the address to represent load_addr.
Definition Address.cpp:1029
@ DumpStyleFileAddress
Display as the file address (if any).
Definition Address.h:87
@ DumpStyleSectionNameOffset
Display as the section name + offset.
Definition Address.h:74
@ DumpStyleDetailedSymbolContext
Detailed symbol context information for an address for all symbol context members.
Definition Address.h:112
@ DumpStyleInvalid
Invalid dump style.
Definition Address.h:68
@ DumpStyleModuleWithFileAddress
Display as the file address with the module name prepended (if any).
Definition Address.h:93
@ DumpStyleResolvedDescription
Display the details about what an address resolves to.
Definition Address.h:104
bool Dump(Stream *s, ExecutionContextScope *exe_scope, DumpStyle style, DumpStyle fallback_style=DumpStyleInvalid, uint32_t addr_byte_size=UINT32_MAX, bool all_ranges=false, std::optional< Stream::HighlightSettings > settings=std::nullopt) const
Dump a description of this object to a Stream.
Definition Address.cpp:398
lldb::ModuleSP GetModule() const
Get accessor for the module for this address.
Definition Address.cpp:275
lldb::addr_t GetFileAddress() const
Get the file address.
Definition Address.cpp:283
bool IsValid() const
Check if the object state is valid.
Definition Address.h:355
An architecture specification class.
Definition ArchSpec.h:32
uint32_t GetAddressByteSize() const
Returns the size in bytes of an address of the current architecture.
Definition ArchSpec.cpp:894
bool IsValid() const
Tests if this ArchSpec is valid.
Definition ArchSpec.h:455
void DumpTriple(llvm::raw_ostream &s) const
const char * GetArchitectureName() const
Returns a static string representing the current architecture.
Definition ArchSpec.cpp:745
A command line argument class.
Definition Args.h:33
void Shift()
Shifts the first argument C string value of the array off the argument array.
Definition Args.cpp:295
size_t GetArgumentCount() const
Gets the number of arguments left in this command object.
Definition Args.h:120
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
static bool InvokeCommonCompletionCallbacks(CommandInterpreter &interpreter, uint32_t completion_mask, lldb_private::CompletionRequest &request, SearchFilter *searcher)
bool Confirm(llvm::StringRef message, bool default_answer)
ExecutionContext GetExecutionContext(bool adopt_dummy_target=true) const
Returns the execution context the interpreter should run a command in.
CommandObjectMultiwordTarget(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)
std::vector< CommandArgumentData > CommandArgumentEntry
virtual void SetHelpLong(llvm::StringRef str)
void AddSimpleArgumentList(lldb::CommandArgumentType arg_type, ArgumentRepetitionType repetition_type=eArgRepeatPlain)
virtual const char * GetInvalidTargetDescription()
std::vector< CommandArgumentEntry > m_arguments
CommandInterpreter & GetCommandInterpreter()
CommandInterpreter & m_interpreter
virtual void HandleArgumentCompletion(CompletionRequest &request, OptionElementVector &opt_element_vector)
The default version handles argument definitions that have only one argument type,...
Target * GetTarget()
Get the target this command should operate on.
void AppendMessage(llvm::StringRef in_string)
void AppendError(llvm::StringRef in_string)
const ValueObjectList & GetValueObjectList() const
void AppendWarningWithFormatv(const char *format, Args &&...args)
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)
A class that describes a compilation unit.
Definition CompileUnit.h:43
lldb::VariableListSP GetVariableList(bool can_create)
Get the variable list for a compile unit.
const FileSpec & GetPrimaryFile() const
Return the primary source spec associated with this compile unit.
"lldb/Utility/ArgCompletionRequest.h"
void TryCompleteCurrentArg(llvm::StringRef completion, llvm::StringRef description="")
Adds a possible completion string if the completion would complete the current argument.
A uniqued constant string class.
Definition ConstString.h:40
bool IsEmpty() const
Test for empty string.
llvm::StringRef GetStringRef() const
Get the string value as a llvm::StringRef.
const char * GetCString() const
Get the string value as a C string.
A class to manage flag bits.
Definition Debugger.h:101
TargetList & GetTargetList()
Get accessor for the target list.
Definition Debugger.h:221
bool GetUseColor() const
Definition Debugger.cpp:543
llvm::StringRef GetRegexMatchAnsiSuffix() const
Definition Debugger.cpp:685
Target & GetDummyTarget()
Definition Debugger.h:561
llvm::StringRef GetRegexMatchAnsiPrefix() const
Definition Debugger.cpp:679
ScriptInterpreter * GetScriptInterpreter(bool can_create=true, std::optional< lldb::ScriptLanguage > language={})
DumpValueObjectOptions & SetRootValueObjectName(const char *name=nullptr)
DumpValueObjectOptions & SetFormat(lldb::Format format=lldb::eFormatDefault)
A class that measures elapsed time in an exception safe way.
Definition Statistics.h:76
"lldb/Target/ExecutionContextScope.h" Inherit from this if your object can reconstruct its execution ...
"lldb/Target/ExecutionContext.h" A class that contains an execution context.
ExecutionContextScope * GetBestExecutionContextScope() const
Target * GetTargetPtr() const
Returns a pointer to the target object.
A file collection class.
const FileSpec & GetFileSpecAtIndex(size_t idx) const
Get file at index.
size_t GetSize() const
Get the number of files in the file list.
A file utility class.
Definition FileSpec.h:56
void SetFile(llvm::StringRef path, Style style)
Change the file specified with a new path.
Definition FileSpec.cpp:174
llvm::StringRef GetFileNameStrippingExtension() const
Return the filename without the extension part.
Definition FileSpec.cpp:414
void SetFilename(llvm::StringRef filename)
Filename string set accessor.
Definition FileSpec.cpp:363
llvm::StringRef GetFilename() const
Filename string const get accessor.
Definition FileSpec.h:248
llvm::StringRef GetDirectory() const
Directory string const get accessor.
Definition FileSpec.h:233
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
Definition FileSpec.cpp:380
void SetDirectory(llvm::StringRef directory)
Directory string set accessor.
Definition FileSpec.cpp:358
void Dump(llvm::raw_ostream &s) const
Dump this object to a Stream.
Definition FileSpec.cpp:341
bool ResolveExecutableLocation(FileSpec &file_spec)
Call into the Host to see if it can help find the file.
bool Exists(const FileSpec &file_spec) const
Returns whether the given file exists.
int Open(const char *path, int flags, int mode=0600)
Wraps open in a platform-independent way.
static FileSystem & Instance()
void Resolve(llvm::SmallVectorImpl< char > &path, bool force_make_absolute=false)
Resolve path to make it canonical.
IOHandlerDelegateMultiline(llvm::StringRef end_line, Completion completion=Completion::None)
Definition IOHandler.h:289
A delegate class for use with IOHandler subclasses.
Definition IOHandler.h:184
lldb::LockableStreamFileSP GetErrorStreamFileSP()
Definition IOHandler.cpp:95
lldb::LockableStreamFileSP GetOutputStreamFileSP()
Definition IOHandler.cpp:93
void SetIsDone(bool b)
Definition IOHandler.h:81
A line table class.
Definition LineTable.h:25
void GetDescription(Stream *s, Target *target, lldb::DescriptionLevel level)
A collection class for Module objects.
Definition ModuleList.h:128
void FindFunctions(ConstString name, lldb::FunctionNameType name_type_mask, const ModuleFunctionSearchOptions &options, SymbolContextList &sc_list) const
ModuleIterableNoLocking ModulesNoLocking() const
Definition ModuleList.h:580
static bool ModuleIsInCache(const Module *module_ptr)
void FindGlobalVariables(ConstString name, size_t max_matches, VariableList &variable_list) const
Find global and static variables by name.
std::recursive_mutex & GetMutex() const
Definition ModuleList.h:255
lldb::ModuleSP FindFirstModule(const ModuleSpec &module_spec) const
Finds the first module whose file specification matches module_spec.
lldb::ModuleSP GetModuleAtIndexUnlocked(size_t idx) const
Get the module shared pointer for the module at index idx without acquiring the ModuleList mutex.
void FindCompileUnits(const FileSpec &path, SymbolContextList &sc_list) const
Find compile units by partial or full path.
bool AppendIfNeeded(const lldb::ModuleSP &new_module, bool notify=true)
Append a module to the module list, if it is not already there.
Module * GetModulePointerAtIndex(size_t idx) const
Get the module pointer for the module at index idx.
void FindModules(const ModuleSpec &module_spec, ModuleList &matching_module_list) const
Finds modules whose file specification matches module_spec.
lldb::ModuleSP GetModuleAtIndex(size_t idx) const
Get the module shared pointer for the module at index idx.
void Append(const lldb::ModuleSP &module_sp, bool notify=true)
Append a module to the module list.
static size_t RemoveOrphanSharedModules(bool mandatory)
static void FindSharedModules(const ModuleSpec &module_spec, ModuleList &matching_module_list)
bool LoadScriptingResourcesInTarget(Target *target, std::list< Status > &errors, bool continue_on_error=true)
ModuleIterable Modules() const
Definition ModuleList.h:574
size_t GetSize() const
Gets the size of the module list.
bool GetModuleSpecAtIndex(size_t i, ModuleSpec &module_spec) const
Definition ModuleSpec.h:387
bool FindMatchingModuleSpec(const ModuleSpec &module_spec, ModuleSpec &match_module_spec) const
Definition ModuleSpec.h:397
FileSpec & GetPlatformFileSpec()
Definition ModuleSpec.h:70
FileSpec & GetFileSpec()
Definition ModuleSpec.h:58
ArchSpec & GetArchitecture()
Definition ModuleSpec.h:94
FileSpec * GetFileSpecPtr()
Definition ModuleSpec.h:52
FileSpec & GetSymbolFileSpec()
Definition ModuleSpec.h:82
A class that describes an executable image and its associated object and symbol files.
Definition Module.h:91
const lldb_private::UUID & GetUUID()
Get a reference to the UUID value contained in this object.
Definition Module.cpp:337
virtual SymbolFile * GetSymbolFile(bool can_create=true, Stream *feedback_strm=nullptr)
Get the module's symbol file.
Definition Module.cpp:975
static Module * GetAllocatedModuleAtIndex(size_t idx)
Definition Module.cpp:120
static std::recursive_mutex & GetAllocationModuleCollectionMutex()
Definition Module.cpp:103
bool ResolveFileAddress(lldb::addr_t vm_addr, Address &so_addr)
Definition Module.cpp:421
Symtab * GetSymtab(bool can_create=true)
Get the module's symbol table.
Definition Module.cpp:1002
bool MatchesModuleSpec(const ModuleSpec &module_ref)
Definition Module.cpp:1464
static size_t GetNumberAllocatedModules()
Definition Module.cpp:114
const ArchSpec & GetArchitecture() const
Get const accessor for the module architecture.
Definition Module.cpp:1017
std::string GetSpecificationDescription() const
Get the module path and object name.
Definition Module.cpp:1019
const FileSpec & GetFileSpec() const
Get const accessor for the module file specification.
Definition Module.h:447
const llvm::sys::TimePoint & GetModificationTime() const
Definition Module.h:485
A plug-in interface definition class for object file parsers.
Definition ObjectFile.h:46
virtual void Dump(Stream *s)=0
Dump a description of this object to a Stream.
virtual std::vector< LoadableData > GetLoadableData(Target &target)
Loads this objfile to memory.
virtual lldb_private::Address GetEntryPointAddress()
Returns the address of the Entry Point in this object file - if the object file doesn't have an entry...
Definition ObjectFile.h:458
virtual FileSpec & GetFileSpec()
Get accessor to the object file specification.
Definition ObjectFile.h:280
static ModuleSpecList GetModuleSpecifications(const FileSpec &file, lldb::offset_t file_offset, lldb::offset_t file_size, lldb::DataExtractorSP=lldb::DataExtractorSP())
virtual lldb_private::Address GetBaseAddress()
Returns base address of this object file.
Definition ObjectFile.h:468
static const uint32_t OPTION_GROUP_GDB_FMT
static const uint32_t OPTION_GROUP_FORMAT
A command line option parsing protocol class.
Definition Options.h:58
std::vector< Option > m_getopt_table
Definition Options.h:198
bool RemapPath(llvm::StringRef path, std::string &new_path) const
void Insert(llvm::StringRef path, llvm::StringRef replacement, uint32_t insert_idx, bool notify)
void Append(llvm::StringRef path, llvm::StringRef replacement, bool notify)
bool GetPathsAtIndex(uint32_t idx, std::string &path, std::string &new_path) const
void Dump(Stream *s, int pair_index=-1)
static bool DownloadObjectAndSymbolFile(ModuleSpec &module_spec, Status &error, bool force_lookup=true, bool copy_executable=true)
void SetExecutableFile(const FileSpec &exe_file, bool add_exe_file_as_first_arg)
A plug-in interface definition class for debugging a process.
Definition Process.h:369
ThreadList & GetThreadList()
Definition Process.h:2370
void Flush()
Flush all data in the process.
Definition Process.cpp:6262
lldb::StateType GetState()
Get accessor for the current process state.
Definition Process.cpp:1319
const lldb::ABISP & GetABI()
Definition Process.cpp:1529
bool IsValid() const
Test if this object contains a valid regular expression.
virtual lldb::ScriptedFrameProviderInterfaceSP CreateScriptedFrameProviderInterface()
lldb::SectionSP FindSectionByName(llvm::StringRef section_name) const
Definition Section.cpp:562
void Dump(llvm::raw_ostream &s, unsigned indent, Target *target, bool show_header, uint32_t depth) const
Definition Section.cpp:648
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 uint32_t GetFrameIndex() const
Query this frame to find what frame it is in this Thread's StackFrameList.
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
const char * AsCString(const char *default_error_str="unknown error") const
Get the error string associated with the current error.
Definition Status.cpp:194
static Status static Status FromErrorStringWithFormatv(const char *format, Args &&...args)
Definition Status.h:151
const char * GetData() const
llvm::StringRef GetString() const
A stream class that can stream formatted output to a file.
Definition Stream.h:28
void Format(const char *format, Args &&... args)
Forwards the arguments to llvm::formatv and writes to the stream.
Definition Stream.h:370
llvm::raw_ostream & AsRawOstream()
Returns a raw_ostream that forwards the data to this Stream object.
Definition Stream.h:405
size_t Indent(llvm::StringRef s="")
Indent the current line in the stream.
Definition Stream.cpp:157
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
Definition Stream.cpp:134
size_t PutCString(llvm::StringRef cstr)
Output a C string to the stream.
Definition Stream.cpp:63
size_t PutChar(char ch)
Definition Stream.cpp:131
void SetIndentLevel(unsigned level)
Set the current indentation level.
Definition Stream.cpp:196
void PutCStringColorHighlighted(llvm::StringRef text, std::optional< HighlightSettings > settings=std::nullopt)
Output a C string to the stream with color highlighting.
Definition Stream.cpp:73
size_t EOL()
Output and End of Line character to the stream.
Definition Stream.cpp:155
void IndentLess(unsigned amount=2)
Decrement the current indentation level.
Definition Stream.cpp:204
void IndentMore(unsigned amount=2)
Increment the current indentation level.
Definition Stream.cpp:201
unsigned GetIndentLevel() const
Get the current indentation level.
Definition Stream.cpp:193
void AddItem(const ObjectSP &item)
bool ForEach(std::function< bool(Object *object)> const &foreach_callback) const
bool GetValueForKeyAsInteger(llvm::StringRef key, IntType &result) const
bool GetValueForKeyAsString(llvm::StringRef key, llvm::StringRef &result) const
bool GetValueForKeyAsArray(llvm::StringRef key, Array *&result) const
void Dump(lldb_private::Stream &s, bool pretty_print=true) const
Defines a list of symbol context objects.
uint32_t GetSize() const
Get accessor for a symbol context list size.
void Append(const SymbolContext &sc)
Append a new symbol context to the list.
Defines a symbol context baton that can be handed other debug core functions.
Function * function
The Function for a given query.
void SortTypeList(TypeMap &type_map, TypeList &type_list) const
Sorts the types in TypeMap according to SymbolContext to TypeList.
lldb::ModuleSP module_sp
The Module for a given query.
CompileUnit * comp_unit
The CompileUnit for a given query.
Symbol * symbol
The Symbol for a given query.
Provides public interface for all SymbolFiles.
Definition SymbolFile.h:51
virtual ObjectFile * GetObjectFile()=0
bool ValueIsAddress() const
Definition Symbol.cpp:191
bool GetByteSizeIsValid() const
Definition Symbol.h:237
Address & GetAddressRef()
Definition Symbol.h:78
lldb::addr_t GetByteSize() const
Definition Symbol.cpp:469
ConstString GetDisplayName() const
Definition Symbol.cpp:199
uint64_t GetRawValue() const
Get the raw value of the symbol from the symbol table.
Definition Symbol.h:119
Symbol * SymbolAtIndex(size_t idx)
Definition Symtab.cpp:225
uint32_t AppendSymbolIndexesWithName(ConstString symbol_name, std::vector< uint32_t > &matches)
Definition Symtab.cpp:679
uint32_t AppendSymbolIndexesMatchingRegExAndType(const RegularExpression &regex, lldb::SymbolType symbol_type, std::vector< uint32_t > &indexes, Mangled::NamePreference name_preference=Mangled::ePreferDemangled)
Definition Symtab.cpp:746
lldb::TargetSP GetTargetAtIndex(uint32_t index) const
Status CreateTarget(Debugger &debugger, llvm::StringRef user_exe_path, llvm::StringRef triple_str, LoadDependentFiles get_dependent_modules, const OptionGroupPlatform *platform_options, lldb::TargetSP &target_sp)
Create a new Target.
void SetSelectedTarget(uint32_t index)
bool DeleteTarget(lldb::TargetSP &target_sp)
Delete a Target object from the list.
lldb::TargetSP GetSelectedTarget()
size_t GetNumTargets() const
bool GetUserSpecifiedTrapHandlerNames(Args &args) const
Definition Target.cpp:5847
Environment GetEnvironment() const
Definition Target.cpp:5482
void SetActionFromStrings(const std::vector< std::string > &strings)
Populate the command list from a vector of individual command strings.
Definition Target.cpp:4591
void SetActionFromString(const std::string &strings)
Definition Target.cpp:4297
void SetActionFromStrings(const std::vector< std::string > &strings)
Definition Target.cpp:4301
Status SetScriptCallback(const ScriptedMetadata &scripted_metadata)
Definition Target.cpp:4343
void ModulesDidLoad(ModuleList &module_list)
This call may preload module symbols, and may do so in parallel depending on the following target set...
Definition Target.cpp:1961
llvm::Expected< uint32_t > AddScriptedFrameProviderDescriptor(const ScriptedFrameProviderDescriptor &descriptor)
Add or update a scripted frame provider descriptor for this target.
Definition Target.cpp:3907
Module * GetExecutableModulePointer()
Definition Target.cpp:1650
bool RemoveHookByID(lldb::user_id_t uid)
Definition Target.cpp:4837
PathMappingList & GetImageSearchPathList()
Definition Target.cpp:2724
size_t GetNumHooks() const
Definition Target.h:1964
std::shared_ptr< StopHook > StopHookSP
Definition Target.h:1774
void SymbolsDidLoad(ModuleList &module_list)
Definition Target.cpp:1989
const std::vector< StopHookSP > GetStopHooks(bool internal=false) const
Definition Target.cpp:3245
const llvm::MapVector< uint32_t, ScriptedFrameProviderDescriptor > & GetScriptedFrameProviderDescriptors() const
Get all scripted frame provider descriptors for this target.
Definition Target.cpp:3968
bool RemoveScriptedFrameProviderDescriptor(uint32_t id)
Remove a scripted frame provider descriptor by id.
Definition Target.cpp:3943
HookSP CreateHook(Hook::HookKind kind)
Definition Target.cpp:4815
void DumpSectionLoadList(Stream &s)
Definition Target.cpp:6127
bool SetHookEnabledStateByID(lldb::user_id_t uid, bool enabled)
Definition Target.cpp:4859
const lldb::ProcessSP & GetProcessSP() const
Definition Target.cpp:330
lldb::ModuleSP GetOrCreateModule(const ModuleSpec &module_spec, bool notify, Status *error_ptr=nullptr, bool invoke_symbol_locators=true)
Find a binary on the system and return its Module, or return an existing Module that is already in th...
Definition Target.cpp:2470
void UndoCreateStopHook(lldb::user_id_t uid)
If you tried to create a stop hook, and that failed, call this to remove the stop hook,...
Definition Target.cpp:3197
bool ResolveLoadAddress(lldb::addr_t load_addr, Address &so_addr, uint32_t stop_id=SectionLoadHistory::eStopIDNow, bool allow_section_end=false)
Definition Target.cpp:3507
HookSP GetHookByID(lldb::user_id_t uid)
Definition Target.cpp:4844
bool SetStopHookActiveStateByID(lldb::user_id_t uid, bool active_state)
Definition Target.cpp:3221
void SetAllStopHooksActiveState(bool active_state)
Definition Target.cpp:3232
StopHookSP CreateStopHook(StopHook::StopHookKind kind, bool internal=false)
Add an empty stop hook to the Target's stop hook list, and returns a shared pointer to the new hook.
Definition Target.cpp:3175
void SetAllHooksEnabledState(bool enabled)
Definition Target.cpp:4867
void UndoCreateHook(lldb::user_id_t uid)
Removes the most recently created hook.
Definition Target.cpp:4830
HookSP GetHookAtIndex(size_t index)
Definition Target.cpp:4851
lldb::PlatformSP GetPlatform()
Definition Target.h:2004
const ModuleList & GetImages() const
Get accessor for the images for this process.
Definition Target.h:1279
const ArchSpec & GetArchitecture() const
Definition Target.h:1321
bool IsDummyTarget() const
Definition Target.h:691
const std::string & GetLabel() const
Definition Target.h:704
void ClearScriptedFrameProviderDescriptors()
Clear all scripted frame provider descriptors for this target.
Definition Target.cpp:3956
std::shared_ptr< Hook > HookSP
Definition Target.h:1945
lldb::ProcessSP CalculateProcess() override
Definition Target.cpp:2713
bool SetSectionLoadAddress(const lldb::SectionSP &section, lldb::addr_t load_addr, bool warn_multiple=false)
Definition Target.cpp:3518
bool RemoveStopHookByID(lldb::user_id_t uid)
Definition Target.cpp:3204
lldb::ThreadSP GetSelectedThread()
uint32_t GetSize(bool can_update=true)
lldb::ThreadSP GetThreadAtIndex(uint32_t idx, bool can_update=true)
void SetIndex(uint32_t index)
Definition ThreadSpec.h:47
void SetName(llvm::StringRef name)
Definition ThreadSpec.h:51
void SetTID(lldb::tid_t tid)
Definition ThreadSpec.h:49
void SetQueueName(llvm::StringRef queue_name)
Definition ThreadSpec.h:53
uint32_t GetSize() const
Definition TypeList.cpp:36
bool Empty() const
Definition TypeList.h:35
TypeIterable Types()
Definition TypeList.h:42
lldb::TypeSP GetTypeAtIndex(uint32_t idx) const
Definition TypeList.cpp:42
A class that contains all state required for type lookups.
Definition Type.h:104
This class tracks the state and results of a TypeQuery.
Definition Type.h:344
TypeMap & GetTypeMap()
Definition Type.h:386
void Dump(Stream &s) const
Definition UUID.cpp:68
std::string GetAsString(llvm::StringRef separator="-") const
Definition UUID.cpp:54
bool IsValid() const
Definition UUID.h:69
lldb::FuncUnwindersSP GetFuncUnwindersContainingAddress(const Address &addr, const SymbolContext &sc)
lldb::FuncUnwindersSP GetUncachedFuncUnwindersContainingAddress(const Address &addr, const SymbolContext &sc)
A collection of ValueObject values that.
void Append(const lldb::ValueObjectSP &val_obj_sp)
lldb::ValueObjectSP GetValueObjectAtIndex(size_t idx)
static lldb::ValueObjectSP Create(ExecutionContextScope *exe_scope, const lldb::VariableSP &var_sp)
lldb::VariableSP GetVariableAtIndex(size_t idx) const
static Status GetValuesForVariableExpressionPath(llvm::StringRef variable_expr_path, ExecutionContextScope *scope, GetVariableCallback callback, void *baton, VariableList &variable_list, ValueObjectList &valobj_list)
Definition Variable.cpp:342
#define LLDB_OPT_SET_1
#define LLDB_OPT_SET_FROM_TO(A, B)
#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_PROCESS_ID
A class that represents a running process on the host machine.
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
Definition Log.h:338
std::vector< OptionArgElement > OptionElementVector
Definition Options.h:43
bool StateIsStoppedState(lldb::StateType state, bool must_exist)
Check if a state represents a state where the process or thread is stopped.
Definition State.cpp:89
void DumpAddress(llvm::raw_ostream &s, uint64_t addr, uint32_t addr_size, const char *prefix=nullptr, const char *suffix=nullptr)
Output an address value to this stream.
Definition Stream.cpp:108
const char * StateAsCString(lldb::StateType state)
Converts a StateType to a C string.
Definition State.cpp:14
std::string toString(FormatterBytecode::OpCodes op)
@ eSourceFileCompletion
std::shared_ptr< lldb_private::TypeSystem > TypeSystemSP
std::shared_ptr< lldb_private::ABI > ABISP
std::shared_ptr< lldb_private::StackFrame > StackFrameSP
DescriptionLevel
Description levels for "void GetDescription(Stream *, DescriptionLevel)" calls.
@ eDescriptionLevelBrief
@ eDescriptionLevelFull
std::shared_ptr< lldb_private::Thread > ThreadSP
std::shared_ptr< lldb_private::ScriptedMetadata > ScriptedMetadataSP
std::shared_ptr< lldb_private::CommandObject > CommandObjectSP
std::shared_ptr< lldb_private::ValueObject > ValueObjectSP
Format
Display format definitions.
std::shared_ptr< lldb_private::Platform > PlatformSP
StateType
Process and Thread States.
std::shared_ptr< lldb_private::FuncUnwinders > FuncUnwindersSP
std::shared_ptr< lldb_private::Type > TypeSP
std::shared_ptr< lldb_private::Process > ProcessSP
@ eReturnStatusFailed
@ eReturnStatusSuccessFinishResult
@ eReturnStatusSuccessFinishNoResult
uint64_t pid_t
Definition lldb-types.h:84
@ eArgTypeOldPathPrefix
@ eArgTypeNewPathPrefix
@ eArgTypeUnsignedInteger
@ eArgTypeDirectoryName
std::shared_ptr< lldb_private::VariableList > VariableListSP
std::shared_ptr< lldb_private::UnwindPlan > UnwindPlanSP
std::shared_ptr< lldb_private::Variable > VariableSP
std::shared_ptr< lldb_private::ScriptedFrameProviderInterface > ScriptedFrameProviderInterfaceSP
@ eValueTypeVariableGlobal
globals variable
@ eValueTypeVariableLocal
function local variables
@ eValueTypeVariableArgument
function argument variables
@ eValueTypeVariableStatic
static variable
@ eValueTypeVariableThreadLocal
thread local storage variable
uint64_t user_id_t
Definition lldb-types.h:83
std::shared_ptr< lldb_private::LockableStreamFile > LockableStreamFileSP
std::shared_ptr< lldb_private::Section > SectionSP
uint64_t addr_t
Definition lldb-types.h:80
std::shared_ptr< lldb_private::Target > TargetSP
std::shared_ptr< lldb_private::RegisterContext > RegisterContextSP
uint64_t tid_t
Definition lldb-types.h:85
std::shared_ptr< lldb_private::Module > ModuleSP
Used to build individual command argument lists.
Options used by Module::FindFunctions.
Definition Module.h:67
bool include_inlines
Include inlined functions.
Definition Module.h:71
bool include_symbols
Include the symbol table.
Definition Module.h:69
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)
This struct contains the metadata needed to instantiate a frame provider and optional filters to cont...
void Dump(Stream *s) const
Dump a description of this descriptor to the given stream.
lldb::ScriptedFrameProviderInterfaceSP interface_sp
Interface for calling static methods on the provider class.
Struct to store information for color highlighting in the stream.
Definition Stream.h:37
#define PATH_MAX