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