LLDB mainline
CommandObjectTarget.cpp
Go to the documentation of this file.
1//===-- CommandObjectTarget.cpp -------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
10
11#include "lldb/Core/Address.h"
12#include "lldb/Core/Debugger.h"
13#include "lldb/Core/IOHandler.h"
14#include "lldb/Core/Module.h"
17#include "lldb/Core/Section.h"
43#include "lldb/Target/ABI.h"
44#include "lldb/Target/Process.h"
48#include "lldb/Target/Thread.h"
50#include "lldb/Utility/Args.h"
54#include "lldb/Utility/State.h"
55#include "lldb/Utility/Stream.h"
57#include "lldb/Utility/Timer.h"
60#include "lldb/lldb-forward.h"
62
63#include "clang/Frontend/CompilerInstance.h"
64#include "clang/Frontend/CompilerInvocation.h"
65#include "clang/Frontend/FrontendActions.h"
66#include "clang/Serialization/ObjectFilePCHContainerReader.h"
67#include "llvm/ADT/ScopeExit.h"
68#include "llvm/ADT/StringRef.h"
69#include "llvm/Support/FileSystem.h"
70#include "llvm/Support/FormatAdapters.h"
71
72
73using namespace lldb;
74using namespace lldb_private;
75
76static void DumpTargetInfo(uint32_t target_idx, Target *target,
77 const char *prefix_cstr,
78 bool show_stopped_process_status, Stream &strm) {
79 const ArchSpec &target_arch = target->GetArchitecture();
80
81 Module *exe_module = target->GetExecutableModulePointer();
82 char exe_path[PATH_MAX];
83 bool exe_valid = false;
84 if (exe_module)
85 exe_valid = exe_module->GetFileSpec().GetPath(exe_path, sizeof(exe_path));
86
87 if (!exe_valid)
88 ::strcpy(exe_path, "<none>");
89
90 std::string formatted_label = "";
91 const std::string &label = target->GetLabel();
92 if (!label.empty()) {
93 formatted_label = " (" + label + ")";
94 }
95
96 strm.Printf("%starget #%u%s: %s", prefix_cstr ? prefix_cstr : "", target_idx,
97 formatted_label.data(), exe_path);
98
99 uint32_t properties = 0;
100 if (target_arch.IsValid()) {
101 strm.Printf(" ( arch=");
102 target_arch.DumpTriple(strm.AsRawOstream());
103 properties++;
104 }
105 PlatformSP platform_sp(target->GetPlatform());
106 if (platform_sp)
107 strm.Format("{0}platform={1}", properties++ > 0 ? ", " : " ( ",
108 platform_sp->GetName());
109
110 ProcessSP process_sp(target->GetProcessSP());
111 bool show_process_status = false;
112 if (process_sp) {
113 lldb::pid_t pid = process_sp->GetID();
114 StateType state = process_sp->GetState();
115 if (show_stopped_process_status)
116 show_process_status = StateIsStoppedState(state, true);
117 const char *state_cstr = StateAsCString(state);
118 if (pid != LLDB_INVALID_PROCESS_ID)
119 strm.Printf("%spid=%" PRIu64, properties++ > 0 ? ", " : " ( ", pid);
120 strm.Printf("%sstate=%s", properties++ > 0 ? ", " : " ( ", state_cstr);
121 }
122 if (properties > 0)
123 strm.PutCString(" )\n");
124 else
125 strm.EOL();
126 if (show_process_status) {
127 const bool only_threads_with_stop_reason = true;
128 const uint32_t start_frame = 0;
129 const uint32_t num_frames = 1;
130 const uint32_t num_frames_with_source = 1;
131 const bool stop_format = false;
132 process_sp->GetStatus(strm);
133 process_sp->GetThreadStatus(strm, only_threads_with_stop_reason,
134 start_frame, num_frames, num_frames_with_source,
135 stop_format);
136 }
137}
138
139static uint32_t DumpTargetList(TargetList &target_list,
140 bool show_stopped_process_status, Stream &strm) {
141 const uint32_t num_targets = target_list.GetNumTargets();
142 if (num_targets) {
143 TargetSP selected_target_sp(target_list.GetSelectedTarget());
144 strm.PutCString("Current targets:\n");
145 for (uint32_t i = 0; i < num_targets; ++i) {
146 TargetSP target_sp(target_list.GetTargetAtIndex(i));
147 if (target_sp) {
148 bool is_selected = target_sp.get() == selected_target_sp.get();
149 DumpTargetInfo(i, target_sp.get(), is_selected ? "* " : " ",
150 show_stopped_process_status, strm);
151 }
152 }
153 }
154 return num_targets;
155}
156
157#define LLDB_OPTIONS_target_dependents
158#include "CommandOptions.inc"
159
161public:
163
164 ~OptionGroupDependents() override = default;
165
166 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
167 return llvm::ArrayRef(g_target_dependents_options);
168 }
169
170 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value,
171 ExecutionContext *execution_context) override {
173
174 // For compatibility no value means don't load dependents.
175 if (option_value.empty()) {
177 return error;
178 }
179
180 const char short_option =
181 g_target_dependents_options[option_idx].short_option;
182 if (short_option == 'd') {
183 LoadDependentFiles tmp_load_dependents;
185 option_value, g_target_dependents_options[option_idx].enum_values, 0,
186 error);
187 if (error.Success())
188 m_load_dependent_files = tmp_load_dependents;
189 } else {
191 "unrecognized short option '%c'", short_option);
192 }
193
194 return error;
195 }
196
197 Status SetOptionValue(uint32_t, const char *, ExecutionContext *) = delete;
198
202
204
205private:
209};
210
211#pragma mark CommandObjectTargetCreate
212
214public:
217 interpreter, "target create",
218 "Create a target using the argument as the main executable.",
219 nullptr),
220 m_platform_options(true), // Include the --platform option.
221 m_core_file(LLDB_OPT_SET_1, false, "core", 'c', 0, eArgTypeFilename,
222 "Fullpath to a core file to use for this target."),
223 m_label(LLDB_OPT_SET_1, false, "label", 'l', 0, eArgTypeName,
224 "Optional name for this target.", nullptr),
225 m_symbol_file(LLDB_OPT_SET_1, false, "symfile", 's', 0,
227 "Fullpath to a stand alone debug "
228 "symbols file for when debug symbols "
229 "are not in the executable."),
231 LLDB_OPT_SET_1, false, "remote-file", 'r', 0, eArgTypeFilename,
232 "Fullpath to the file on the remote host if debugging remotely.") {
233
235
243 m_option_group.Finalize();
244 }
245
246 ~CommandObjectTargetCreate() override = default;
247
248 Options *GetOptions() override { return &m_option_group; }
249
250protected:
251 void DoExecute(Args &command, CommandReturnObject &result) override {
252 const size_t argc = command.GetArgumentCount();
253 FileSpec core_file(m_core_file.GetOptionValue().GetCurrentValue());
254 FileSpec remote_file(m_remote_file.GetOptionValue().GetCurrentValue());
255
256 if (core_file) {
257 auto file = FileSystem::Instance().Open(
259
260 if (!file) {
261 result.AppendErrorWithFormatv("Cannot open '{0}': {1}.",
262 core_file.GetPath(),
263 llvm::toString(file.takeError()));
264 return;
265 }
266 }
267
268 if (argc == 1 || core_file || remote_file) {
269 FileSpec symfile(m_symbol_file.GetOptionValue().GetCurrentValue());
270 if (symfile) {
271 auto file = FileSystem::Instance().Open(
273
274 if (!file) {
275 result.AppendErrorWithFormatv("Cannot open '{0}': {1}.",
276 symfile.GetPath(),
277 llvm::toString(file.takeError()));
278 return;
279 }
280 }
281
282 const char *file_path = command.GetArgumentAtIndex(0);
283 LLDB_SCOPED_TIMERF("(lldb) target create '%s'", file_path);
284
285 bool must_set_platform_path = false;
286
287 Debugger &debugger = GetDebugger();
288
289 TargetSP target_sp;
290 llvm::StringRef arch_cstr = m_arch_option.GetArchitectureName();
292 debugger, file_path, arch_cstr,
293 m_add_dependents.m_load_dependent_files, &m_platform_options,
294 target_sp));
295
296 if (!target_sp) {
297 result.AppendError(error.AsCString());
298 return;
299 }
300
301 const llvm::StringRef label =
302 m_label.GetOptionValue().GetCurrentValueAsRef();
303 if (!label.empty()) {
304 if (auto E = target_sp->SetLabel(label))
305 result.SetError(std::move(E));
306 return;
307 }
308
309 auto on_error = llvm::make_scope_exit(
310 [&target_list = debugger.GetTargetList(), &target_sp]() {
311 target_list.DeleteTarget(target_sp);
312 });
313
314 // Only get the platform after we create the target because we might
315 // have switched platforms depending on what the arguments were to
316 // CreateTarget() we can't rely on the selected platform.
317
318 PlatformSP platform_sp = target_sp->GetPlatform();
319
320 FileSpec file_spec;
321 if (file_path) {
322 file_spec.SetFile(file_path, FileSpec::Style::native);
323 FileSystem::Instance().Resolve(file_spec);
324
325 // Try to resolve the exe based on PATH and/or platform-specific
326 // suffixes, but only if using the host platform.
327 if (platform_sp && platform_sp->IsHost() &&
328 !FileSystem::Instance().Exists(file_spec))
330 }
331
332 if (remote_file) {
333 if (platform_sp) {
334 // I have a remote file.. two possible cases
335 if (file_spec && FileSystem::Instance().Exists(file_spec)) {
336 // if the remote file does not exist, push it there
337 if (!platform_sp->GetFileExists(remote_file)) {
338 Status err = platform_sp->PutFile(file_spec, remote_file);
339 if (err.Fail()) {
340 result.AppendError(err.AsCString());
341 return;
342 }
343 }
344 } else {
345 // there is no local file and we need one
346 // in order to make the remote ---> local transfer we need a
347 // platform
348 // TODO: if the user has passed in a --platform argument, use it
349 // to fetch the right platform
350 if (file_path) {
351 // copy the remote file to the local file
352 Status err = platform_sp->GetFile(remote_file, file_spec);
353 if (err.Fail()) {
354 result.AppendError(err.AsCString());
355 return;
356 }
357 } else {
358 // If the remote file exists, we can debug reading that out of
359 // memory. If the platform is already connected to an lldb-server
360 // then we can at least check the file exists remotely. Otherwise
361 // we'll just have to trust that it will be there when we do
362 // process connect.
363 // I don't do this for the host platform because it seems odd to
364 // support supplying a remote file but no local file for a local
365 // debug session.
366 if (platform_sp->IsHost()) {
367 result.AppendError("Supply a local file, not a remote file, "
368 "when debugging on the host.");
369 return;
370 }
371 if (platform_sp->IsConnected() && !platform_sp->GetFileExists(remote_file)) {
372 result.AppendError("remote --> local transfer without local "
373 "path is not implemented yet");
374 return;
375 }
376 // Since there's only a remote file, we need to set the executable
377 // file spec to the remote one.
378 ProcessLaunchInfo launch_info = target_sp->GetProcessLaunchInfo();
379 launch_info.SetExecutableFile(FileSpec(remote_file), true);
380 target_sp->SetProcessLaunchInfo(launch_info);
381 }
382 }
383 } else {
384 result.AppendError("no platform found for target");
385 return;
386 }
387 }
388
389 if (symfile || remote_file) {
390 ModuleSP module_sp(target_sp->GetExecutableModule());
391 if (module_sp) {
392 if (symfile)
393 module_sp->SetSymbolFileFileSpec(symfile);
394 if (remote_file) {
395 std::string remote_path = remote_file.GetPath();
396 target_sp->SetArg0(remote_path.c_str());
397 module_sp->SetPlatformFileSpec(remote_file);
398 }
399 }
400 }
401
402 if (must_set_platform_path) {
403 ModuleSpec main_module_spec(file_spec);
404 ModuleSP module_sp =
405 target_sp->GetOrCreateModule(main_module_spec, true /* notify */);
406 if (module_sp)
407 module_sp->SetPlatformFileSpec(remote_file);
408 }
409
410 if (core_file) {
411 FileSpec core_file_dir;
412 core_file_dir.SetDirectory(core_file.GetDirectory());
413 target_sp->AppendExecutableSearchPaths(core_file_dir);
414
415 ProcessSP process_sp(target_sp->CreateProcess(
416 GetDebugger().GetListener(), llvm::StringRef(), &core_file, false));
417
418 if (process_sp) {
419 // Seems weird that we Launch a core file, but that is what we
420 // do!
421 error = process_sp->LoadCore();
422
423 if (error.Fail()) {
424 result.AppendError(error.AsCString("unknown core file format"));
425 return;
426 } else {
428 "Core file '{0}' ({1}) was loaded.\n", core_file.GetPath(),
429 target_sp->GetArchitecture().GetArchitectureName());
431 on_error.release();
432 }
433 } else {
434 result.AppendErrorWithFormatv("Unknown core file format '{0}'\n",
435 core_file.GetPath());
436 }
437 } else {
439 "Current executable set to '%s' (%s).\n",
440 file_spec.GetPath().c_str(),
441 target_sp->GetArchitecture().GetArchitectureName());
443 on_error.release();
444 }
445 } else {
446 result.AppendErrorWithFormat("'%s' takes exactly one executable path "
447 "argument, or use the --core option.\n",
448 m_cmd_name.c_str());
449 }
450 }
451
452private:
461};
462
463#pragma mark CommandObjectTargetList
464
466public:
469 interpreter, "target list",
470 "List all current targets in the current debug session.", nullptr) {
471 }
472
473 ~CommandObjectTargetList() override = default;
474
475protected:
476 void DoExecute(Args &args, CommandReturnObject &result) override {
477 Stream &strm = result.GetOutputStream();
478
479 bool show_stopped_process_status = false;
480 if (DumpTargetList(GetDebugger().GetTargetList(),
481 show_stopped_process_status, strm) == 0) {
482 strm.PutCString("No targets.\n");
483 }
485 }
486};
487
488#pragma mark CommandObjectTargetSelect
489
491public:
494 interpreter, "target select",
495 "Select a target as the current target by target index.", nullptr) {
497 }
498
499 ~CommandObjectTargetSelect() override = default;
500
501protected:
502 void DoExecute(Args &args, CommandReturnObject &result) override {
503 if (args.GetArgumentCount() == 1) {
504 const char *target_identifier = args.GetArgumentAtIndex(0);
505 uint32_t target_idx = LLDB_INVALID_INDEX32;
506 TargetList &target_list = GetDebugger().GetTargetList();
507 const uint32_t num_targets = target_list.GetNumTargets();
508 if (llvm::to_integer(target_identifier, target_idx)) {
509 if (target_idx < num_targets) {
510 target_list.SetSelectedTarget(target_idx);
511 Stream &strm = result.GetOutputStream();
512 bool show_stopped_process_status = false;
513 DumpTargetList(target_list, show_stopped_process_status, strm);
515 } else {
516 if (num_targets > 0) {
518 "index %u is out of range, valid target indexes are 0 - %u\n",
519 target_idx, num_targets - 1);
520 } else {
522 "index %u is out of range since there are no active targets\n",
523 target_idx);
524 }
525 }
526 } else {
527 for (size_t i = 0; i < num_targets; i++) {
528 if (TargetSP target_sp = target_list.GetTargetAtIndex(i)) {
529 const std::string &label = target_sp->GetLabel();
530 if (!label.empty() && label == target_identifier) {
531 target_idx = i;
532 break;
533 }
534 }
535 }
536
537 if (target_idx != LLDB_INVALID_INDEX32) {
538 target_list.SetSelectedTarget(target_idx);
539 Stream &strm = result.GetOutputStream();
540 bool show_stopped_process_status = false;
541 DumpTargetList(target_list, show_stopped_process_status, strm);
543 } else {
544 result.AppendErrorWithFormat("invalid index string value '%s'\n",
545 target_identifier);
546 }
547 }
548 } else {
549 result.AppendError(
550 "'target select' takes a single argument: a target index\n");
551 }
552 }
553};
554
555#pragma mark CommandObjectTargetDelete
556
558public:
560 : CommandObjectParsed(interpreter, "target delete",
561 "Delete one or more targets by target index.",
562 nullptr),
563 m_all_option(LLDB_OPT_SET_1, false, "all", 'a', "Delete all targets.",
564 false, true),
566 LLDB_OPT_SET_1, false, "clean", 'c',
567 "Perform extra cleanup to minimize memory consumption after "
568 "deleting the target. "
569 "By default, LLDB will keep in memory any modules previously "
570 "loaded by the target as well "
571 "as all of its debug info. Specifying --clean will unload all of "
572 "these shared modules and "
573 "cause them to be reparsed again the next time the target is run",
574 false, true) {
577 m_option_group.Finalize();
579 }
580
581 ~CommandObjectTargetDelete() override = default;
582
583 Options *GetOptions() override { return &m_option_group; }
584
585protected:
586 void DoExecute(Args &args, CommandReturnObject &result) override {
587 const size_t argc = args.GetArgumentCount();
588 std::vector<TargetSP> delete_target_list;
589 TargetList &target_list = GetDebugger().GetTargetList();
590 TargetSP target_sp;
591
592 if (m_all_option.GetOptionValue()) {
593 for (size_t i = 0; i < target_list.GetNumTargets(); ++i)
594 delete_target_list.push_back(target_list.GetTargetAtIndex(i));
595 } else if (argc > 0) {
596 const uint32_t num_targets = target_list.GetNumTargets();
597 // Bail out if don't have any targets.
598 if (num_targets == 0) {
599 result.AppendError("no targets to delete");
600 return;
601 }
602
603 for (auto &entry : args.entries()) {
604 uint32_t target_idx;
605 if (entry.ref().getAsInteger(0, target_idx)) {
606 result.AppendErrorWithFormat("invalid target index '%s'\n",
607 entry.c_str());
608 return;
609 }
610 if (target_idx < num_targets) {
611 target_sp = target_list.GetTargetAtIndex(target_idx);
612 if (target_sp) {
613 delete_target_list.push_back(target_sp);
614 continue;
615 }
616 }
617 if (num_targets > 1)
618 result.AppendErrorWithFormat("target index %u is out of range, valid "
619 "target indexes are 0 - %u\n",
620 target_idx, num_targets - 1);
621 else
623 "target index %u is out of range, the only valid index is 0\n",
624 target_idx);
625
626 return;
627 }
628 } else {
629 target_sp = target_list.GetSelectedTarget();
630 if (!target_sp) {
631 result.AppendErrorWithFormat("no target is currently selected\n");
632 return;
633 }
634 delete_target_list.push_back(target_sp);
635 }
636
637 const size_t num_targets_to_delete = delete_target_list.size();
638 for (size_t idx = 0; idx < num_targets_to_delete; ++idx) {
639 target_sp = delete_target_list[idx];
640 target_list.DeleteTarget(target_sp);
641 target_sp->Destroy();
642 }
643 // If "--clean" was specified, prune any orphaned shared modules from the
644 // global shared module list
645 if (m_cleanup_option.GetOptionValue()) {
646 const bool mandatory = true;
648 }
649 result.GetOutputStream().Printf("%u targets deleted.\n",
650 (uint32_t)num_targets_to_delete);
652 }
653
657};
658
660public:
663 interpreter, "target show-launch-environment",
664 "Shows the environment being passed to the process when launched, "
665 "taking info account 3 settings: target.env-vars, "
666 "target.inherit-env and target.unset-env-vars.",
667 nullptr, eCommandRequiresTarget) {}
668
670
671protected:
672 void DoExecute(Args &args, CommandReturnObject &result) override {
673 Target *target = m_exe_ctx.GetTargetPtr();
674 Environment env = target->GetEnvironment();
675
676 std::vector<Environment::value_type *> env_vector;
677 env_vector.reserve(env.size());
678 for (auto &KV : env)
679 env_vector.push_back(&KV);
680 std::sort(env_vector.begin(), env_vector.end(),
681 [](Environment::value_type *a, Environment::value_type *b) {
682 return a->first() < b->first();
683 });
684
685 auto &strm = result.GetOutputStream();
686 for (auto &KV : env_vector)
687 strm.Format("{0}={1}\n", KV->first(), KV->second);
688
690 }
691};
692
693#pragma mark CommandObjectTargetVariable
694
696 static const uint32_t SHORT_OPTION_FILE = 0x66696c65; // 'file'
697 static const uint32_t SHORT_OPTION_SHLB = 0x73686c62; // 'shlb'
698
699public:
701 : CommandObjectParsed(interpreter, "target variable",
702 "Read global variables for the current target, "
703 "before or while running a process.",
704 nullptr, eCommandRequiresTarget),
705 m_option_variable(false), // Don't include frame options
709 "A basename or fullpath to a file that contains "
710 "global variables. This option can be "
711 "specified multiple times."),
713 LLDB_OPT_SET_1, false, "shlib", SHORT_OPTION_SHLB, 0,
715 "A basename or fullpath to a shared library to use in the search "
716 "for global "
717 "variables. This option can be specified multiple times.") {
719
730 m_option_group.Finalize();
731 }
732
733 ~CommandObjectTargetVariable() override = default;
734
735 void DumpValueObject(Stream &s, VariableSP &var_sp, ValueObjectSP &valobj_sp,
736 const char *root_name) {
737 DumpValueObjectOptions options(m_varobj_options.GetAsDumpOptions());
738
739 if (!valobj_sp->GetTargetSP()->GetDisplayRuntimeSupportValues() &&
740 valobj_sp->IsRuntimeSupportValue())
741 return;
742
743 switch (var_sp->GetScope()) {
745 if (m_option_variable.show_scope)
746 s.PutCString("GLOBAL: ");
747 break;
748
750 if (m_option_variable.show_scope)
751 s.PutCString("STATIC: ");
752 break;
753
755 if (m_option_variable.show_scope)
756 s.PutCString(" ARG: ");
757 break;
758
760 if (m_option_variable.show_scope)
761 s.PutCString(" LOCAL: ");
762 break;
763
765 if (m_option_variable.show_scope)
766 s.PutCString("THREAD: ");
767 break;
768
769 default:
770 break;
771 }
772
773 if (m_option_variable.show_decl) {
774 bool show_fullpaths = false;
775 bool show_module = true;
776 if (var_sp->DumpDeclaration(&s, show_fullpaths, show_module))
777 s.PutCString(": ");
778 }
779
780 const Format format = m_option_format.GetFormat();
781 if (format != eFormatDefault)
782 options.SetFormat(format);
783
784 options.SetRootValueObjectName(root_name);
785
786 if (llvm::Error error = valobj_sp->Dump(s, options))
787 s << "error: " << toString(std::move(error));
788 }
789
790 static size_t GetVariableCallback(void *baton, const char *name,
791 VariableList &variable_list) {
792 size_t old_size = variable_list.GetSize();
793 Target *target = static_cast<Target *>(baton);
794 if (target)
796 variable_list);
797 return variable_list.GetSize() - old_size;
798 }
799
800 Options *GetOptions() override { return &m_option_group; }
801
802protected:
804 const SymbolContext &sc,
805 const VariableList &variable_list,
806 CommandReturnObject &result) {
807 Stream &s = result.GetOutputStream();
808 if (variable_list.Empty())
809 return;
810 if (sc.module_sp) {
811 if (sc.comp_unit) {
812 s.Format("Global variables for {0} in {1}:\n",
813 sc.comp_unit->GetPrimaryFile(), sc.module_sp->GetFileSpec());
814 } else {
815 s.Printf("Global variables for %s\n",
816 sc.module_sp->GetFileSpec().GetPath().c_str());
817 }
818 } else if (sc.comp_unit) {
819 s.Format("Global variables for {0}\n", sc.comp_unit->GetPrimaryFile());
820 }
821
822 for (VariableSP var_sp : variable_list) {
823 if (!var_sp)
824 continue;
826 exe_ctx.GetBestExecutionContextScope(), var_sp));
827
828 if (valobj_sp) {
829 result.GetValueObjectList().Append(valobj_sp);
830 DumpValueObject(s, var_sp, valobj_sp, var_sp->GetName().GetCString());
831 }
832 }
833 }
834
835 void DoExecute(Args &args, CommandReturnObject &result) override {
836 Target *target = m_exe_ctx.GetTargetPtr();
837 const size_t argc = args.GetArgumentCount();
838
839 if (argc > 0) {
840 for (const Args::ArgEntry &arg : args) {
841 VariableList variable_list;
842 ValueObjectList valobj_list;
843
844 size_t matches = 0;
845 bool use_var_name = false;
846 if (m_option_variable.use_regex) {
847 RegularExpression regex(arg.ref());
848 if (!regex.IsValid()) {
849 result.GetErrorStream().Printf(
850 "error: invalid regular expression: '%s'\n", arg.c_str());
851 return;
852 }
853 use_var_name = true;
855 variable_list);
856 matches = variable_list.GetSize();
857 } else {
859 arg.c_str(), m_exe_ctx.GetBestExecutionContextScope(),
860 GetVariableCallback, target, variable_list, valobj_list));
861 matches = variable_list.GetSize();
862 }
863
864 if (matches == 0) {
865 result.AppendErrorWithFormat("can't find global variable '%s'",
866 arg.c_str());
867 return;
868 } else {
869 for (uint32_t global_idx = 0; global_idx < matches; ++global_idx) {
870 VariableSP var_sp(variable_list.GetVariableAtIndex(global_idx));
871 if (var_sp) {
872 ValueObjectSP valobj_sp(
873 valobj_list.GetValueObjectAtIndex(global_idx));
874 if (!valobj_sp)
875 valobj_sp = ValueObjectVariable::Create(
876 m_exe_ctx.GetBestExecutionContextScope(), var_sp);
877
878 if (valobj_sp)
879 DumpValueObject(result.GetOutputStream(), var_sp, valobj_sp,
880 use_var_name ? var_sp->GetName().GetCString()
881 : arg.c_str());
882 }
883 }
884 }
885 }
886 } else {
887 const FileSpecList &compile_units =
888 m_option_compile_units.GetOptionValue().GetCurrentValue();
889 const FileSpecList &shlibs =
890 m_option_shared_libraries.GetOptionValue().GetCurrentValue();
891 SymbolContextList sc_list;
892 const size_t num_compile_units = compile_units.GetSize();
893 const size_t num_shlibs = shlibs.GetSize();
894 if (num_compile_units == 0 && num_shlibs == 0) {
895 bool success = false;
896 StackFrame *frame = m_exe_ctx.GetFramePtr();
897 CompileUnit *comp_unit = nullptr;
898 if (frame) {
899 SymbolContext sc = frame->GetSymbolContext(eSymbolContextCompUnit);
900 comp_unit = sc.comp_unit;
901 if (sc.comp_unit) {
902 const bool can_create = true;
903 VariableListSP comp_unit_varlist_sp(
904 sc.comp_unit->GetVariableList(can_create));
905 if (comp_unit_varlist_sp) {
906 size_t count = comp_unit_varlist_sp->GetSize();
907 if (count > 0) {
908 DumpGlobalVariableList(m_exe_ctx, sc, *comp_unit_varlist_sp,
909 result);
910 success = true;
911 }
912 }
913 }
914 }
915 if (!success) {
916 if (frame) {
917 if (comp_unit)
919 "no global variables in current compile unit: {0}\n",
920 comp_unit->GetPrimaryFile());
921 else
923 "no debug information for frame %u\n",
924 frame->GetFrameIndex());
925 } else
926 result.AppendError("'target variable' takes one or more global "
927 "variable names as arguments\n");
928 }
929 } else {
930 SymbolContextList sc_list;
931 // We have one or more compile unit or shlib
932 if (num_shlibs > 0) {
933 for (size_t shlib_idx = 0; shlib_idx < num_shlibs; ++shlib_idx) {
934 const FileSpec module_file(shlibs.GetFileSpecAtIndex(shlib_idx));
935 ModuleSpec module_spec(module_file);
936
937 ModuleSP module_sp(
938 target->GetImages().FindFirstModule(module_spec));
939 if (module_sp) {
940 if (num_compile_units > 0) {
941 for (size_t cu_idx = 0; cu_idx < num_compile_units; ++cu_idx)
942 module_sp->FindCompileUnits(
943 compile_units.GetFileSpecAtIndex(cu_idx), sc_list);
944 } else {
945 SymbolContext sc;
946 sc.module_sp = module_sp;
947 sc_list.Append(sc);
948 }
949 } else {
950 // Didn't find matching shlib/module in target...
952 "target doesn't contain the specified shared library: %s\n",
953 module_file.GetPath().c_str());
954 }
955 }
956 } else {
957 // No shared libraries, we just want to find globals for the compile
958 // units files that were specified
959 for (size_t cu_idx = 0; cu_idx < num_compile_units; ++cu_idx)
960 target->GetImages().FindCompileUnits(
961 compile_units.GetFileSpecAtIndex(cu_idx), sc_list);
962 }
963
964 for (const SymbolContext &sc : sc_list) {
965 if (sc.comp_unit) {
966 const bool can_create = true;
967 VariableListSP comp_unit_varlist_sp(
968 sc.comp_unit->GetVariableList(can_create));
969 if (comp_unit_varlist_sp)
970 DumpGlobalVariableList(m_exe_ctx, sc, *comp_unit_varlist_sp,
971 result);
972 } else if (sc.module_sp) {
973 // Get all global variables for this module
974 lldb_private::RegularExpression all_globals_regex(
975 llvm::StringRef(".")); // Any global with at least one character
976 VariableList variable_list;
977 sc.module_sp->FindGlobalVariables(all_globals_regex, UINT32_MAX,
978 variable_list);
979 DumpGlobalVariableList(m_exe_ctx, sc, variable_list, result);
980 }
981 }
982 }
983 }
984
985 m_interpreter.PrintWarningsIfNecessary(result.GetOutputStream(),
986 m_cmd_name);
987 }
988
995};
996
997#pragma mark CommandObjectTargetModulesSearchPathsAdd
998
1000public:
1002 : CommandObjectParsed(interpreter, "target modules search-paths add",
1003 "Add new image search paths substitution pairs to "
1004 "the current target.",
1005 nullptr, eCommandRequiresTarget) {
1007 CommandArgumentData old_prefix_arg;
1008 CommandArgumentData new_prefix_arg;
1009
1010 // Define the first variant of this arg pair.
1011 old_prefix_arg.arg_type = eArgTypeOldPathPrefix;
1012 old_prefix_arg.arg_repetition = eArgRepeatPairPlus;
1013
1014 // Define the first variant of this arg pair.
1015 new_prefix_arg.arg_type = eArgTypeNewPathPrefix;
1016 new_prefix_arg.arg_repetition = eArgRepeatPairPlus;
1017
1018 // There are two required arguments that must always occur together, i.e.
1019 // an argument "pair". Because they must always occur together, they are
1020 // treated as two variants of one argument rather than two independent
1021 // arguments. Push them both into the first argument position for
1022 // m_arguments...
1023
1024 arg.push_back(old_prefix_arg);
1025 arg.push_back(new_prefix_arg);
1026
1027 m_arguments.push_back(arg);
1028 }
1029
1031
1032protected:
1033 void DoExecute(Args &command, CommandReturnObject &result) override {
1034 Target &target = GetTarget();
1035 const size_t argc = command.GetArgumentCount();
1036 if (argc & 1) {
1037 result.AppendError("add requires an even number of arguments\n");
1038 } else {
1039 for (size_t i = 0; i < argc; i += 2) {
1040 const char *from = command.GetArgumentAtIndex(i);
1041 const char *to = command.GetArgumentAtIndex(i + 1);
1042
1043 if (from[0] && to[0]) {
1044 Log *log = GetLog(LLDBLog::Host);
1045 if (log) {
1046 LLDB_LOGF(log,
1047 "target modules search path adding ImageSearchPath "
1048 "pair: '%s' -> '%s'",
1049 from, to);
1050 }
1051 bool last_pair = ((argc - i) == 2);
1053 from, to, last_pair); // Notify if this is the last pair
1055 } else {
1056 if (from[0])
1057 result.AppendError("<path-prefix> can't be empty\n");
1058 else
1059 result.AppendError("<new-path-prefix> can't be empty\n");
1060 }
1061 }
1062 }
1063 }
1064};
1065
1066#pragma mark CommandObjectTargetModulesSearchPathsClear
1067
1069public:
1071 : CommandObjectParsed(interpreter, "target modules search-paths clear",
1072 "Clear all current image search path substitution "
1073 "pairs from the current target.",
1074 "target modules search-paths clear",
1075 eCommandRequiresTarget) {}
1076
1078
1079protected:
1080 void DoExecute(Args &command, CommandReturnObject &result) override {
1081 Target &target = GetTarget();
1082 bool notify = true;
1083 target.GetImageSearchPathList().Clear(notify);
1085 }
1086};
1087
1088#pragma mark CommandObjectTargetModulesSearchPathsInsert
1089
1091public:
1093 : CommandObjectParsed(interpreter, "target modules search-paths insert",
1094 "Insert a new image search path substitution pair "
1095 "into the current target at the specified index.",
1096 nullptr, eCommandRequiresTarget) {
1099 CommandArgumentData index_arg;
1100 CommandArgumentData old_prefix_arg;
1101 CommandArgumentData new_prefix_arg;
1102
1103 // Define the first and only variant of this arg.
1104 index_arg.arg_type = eArgTypeIndex;
1105 index_arg.arg_repetition = eArgRepeatPlain;
1106
1107 // Put the one and only variant into the first arg for m_arguments:
1108 arg1.push_back(index_arg);
1109
1110 // Define the first variant of this arg pair.
1111 old_prefix_arg.arg_type = eArgTypeOldPathPrefix;
1112 old_prefix_arg.arg_repetition = eArgRepeatPairPlus;
1113
1114 // Define the first variant of this arg pair.
1115 new_prefix_arg.arg_type = eArgTypeNewPathPrefix;
1116 new_prefix_arg.arg_repetition = eArgRepeatPairPlus;
1117
1118 // There are two required arguments that must always occur together, i.e.
1119 // an argument "pair". Because they must always occur together, they are
1120 // treated as two variants of one argument rather than two independent
1121 // arguments. Push them both into the same argument position for
1122 // m_arguments...
1123
1124 arg2.push_back(old_prefix_arg);
1125 arg2.push_back(new_prefix_arg);
1126
1127 // Add arguments to m_arguments.
1128 m_arguments.push_back(arg1);
1129 m_arguments.push_back(arg2);
1130 }
1131
1133
1134 void
1136 OptionElementVector &opt_element_vector) override {
1137 if (!m_exe_ctx.HasTargetScope() || request.GetCursorIndex() != 0)
1138 return;
1139
1140 Target *target = m_exe_ctx.GetTargetPtr();
1141 const PathMappingList &list = target->GetImageSearchPathList();
1142 const size_t num = list.GetSize();
1143 ConstString old_path, new_path;
1144 for (size_t i = 0; i < num; ++i) {
1145 if (!list.GetPathsAtIndex(i, old_path, new_path))
1146 break;
1147 StreamString strm;
1148 strm << old_path << " -> " << new_path;
1149 request.TryCompleteCurrentArg(std::to_string(i), strm.GetString());
1150 }
1151 }
1152
1153protected:
1154 void DoExecute(Args &command, CommandReturnObject &result) override {
1155 Target &target = GetTarget();
1156 size_t argc = command.GetArgumentCount();
1157 // check for at least 3 arguments and an odd number of parameters
1158 if (argc >= 3 && argc & 1) {
1159 uint32_t insert_idx;
1160
1161 if (!llvm::to_integer(command.GetArgumentAtIndex(0), insert_idx)) {
1162 result.AppendErrorWithFormat(
1163 "<index> parameter is not an integer: '%s'.\n",
1164 command.GetArgumentAtIndex(0));
1165 return;
1166 }
1167
1168 // shift off the index
1169 command.Shift();
1170 argc = command.GetArgumentCount();
1171
1172 for (uint32_t i = 0; i < argc; i += 2, ++insert_idx) {
1173 const char *from = command.GetArgumentAtIndex(i);
1174 const char *to = command.GetArgumentAtIndex(i + 1);
1175
1176 if (from[0] && to[0]) {
1177 bool last_pair = ((argc - i) == 2);
1178 target.GetImageSearchPathList().Insert(from, to, insert_idx,
1179 last_pair);
1181 } else {
1182 if (from[0])
1183 result.AppendError("<path-prefix> can't be empty\n");
1184 else
1185 result.AppendError("<new-path-prefix> can't be empty\n");
1186 return;
1187 }
1188 }
1189 } else {
1190 result.AppendError("insert requires at least three arguments\n");
1191 }
1192 }
1193};
1194
1195#pragma mark CommandObjectTargetModulesSearchPathsList
1196
1198public:
1200 : CommandObjectParsed(interpreter, "target modules search-paths list",
1201 "List all current image search path substitution "
1202 "pairs in the current target.",
1203 "target modules search-paths list",
1204 eCommandRequiresTarget) {}
1205
1207
1208protected:
1209 void DoExecute(Args &command, CommandReturnObject &result) override {
1210 Target &target = GetTarget();
1211 target.GetImageSearchPathList().Dump(&result.GetOutputStream());
1213 }
1214};
1215
1216#pragma mark CommandObjectTargetModulesSearchPathsQuery
1217
1219public:
1222 interpreter, "target modules search-paths query",
1223 "Transform a path using the first applicable image search path.",
1224 nullptr, eCommandRequiresTarget) {
1226 }
1227
1229
1230protected:
1231 void DoExecute(Args &command, CommandReturnObject &result) override {
1232 Target &target = GetTarget();
1233 if (command.GetArgumentCount() != 1) {
1234 result.AppendError("query requires one argument\n");
1235 return;
1236 }
1237
1238 ConstString orig(command.GetArgumentAtIndex(0));
1239 ConstString transformed;
1240 if (target.GetImageSearchPathList().RemapPath(orig, transformed))
1241 result.GetOutputStream().Printf("%s\n", transformed.GetCString());
1242 else
1243 result.GetOutputStream().Printf("%s\n", orig.GetCString());
1244
1246 }
1247};
1248
1249// Static Helper functions
1250static void DumpModuleArchitecture(Stream &strm, Module *module,
1251 bool full_triple, uint32_t width) {
1252 if (module) {
1253 StreamString arch_strm;
1254
1255 if (full_triple)
1256 module->GetArchitecture().DumpTriple(arch_strm.AsRawOstream());
1257 else
1258 arch_strm.PutCString(module->GetArchitecture().GetArchitectureName());
1259 std::string arch_str = std::string(arch_strm.GetString());
1260
1261 if (width)
1262 strm.Printf("%-*s", width, arch_str.c_str());
1263 else
1264 strm.PutCString(arch_str);
1265 }
1266}
1267
1268static void DumpModuleUUID(Stream &strm, Module *module) {
1269 if (module && module->GetUUID().IsValid())
1270 module->GetUUID().Dump(strm);
1271 else
1272 strm.PutCString(" ");
1273}
1274
1276 Stream &strm, Module *module,
1277 const FileSpec &file_spec,
1278 lldb::DescriptionLevel desc_level) {
1279 uint32_t num_matches = 0;
1280 if (module) {
1281 SymbolContextList sc_list;
1282 num_matches = module->ResolveSymbolContextsForFileSpec(
1283 file_spec, 0, false, eSymbolContextCompUnit, sc_list);
1284
1285 bool first_module = true;
1286 for (const SymbolContext &sc : sc_list) {
1287 if (!first_module)
1288 strm << "\n\n";
1289
1290 strm << "Line table for " << sc.comp_unit->GetPrimaryFile() << " in `"
1291 << module->GetFileSpec().GetFilename() << "\n";
1292 LineTable *line_table = sc.comp_unit->GetLineTable();
1293 if (line_table)
1294 line_table->GetDescription(
1295 &strm, interpreter.GetExecutionContext().GetTargetPtr(),
1296 desc_level);
1297 else
1298 strm << "No line table";
1299
1300 first_module = false;
1301 }
1302 }
1303 return num_matches;
1304}
1305
1306static void DumpFullpath(Stream &strm, const FileSpec *file_spec_ptr,
1307 uint32_t width) {
1308 if (file_spec_ptr) {
1309 if (width > 0) {
1310 std::string fullpath = file_spec_ptr->GetPath();
1311 strm.Printf("%-*s", width, fullpath.c_str());
1312 return;
1313 } else {
1314 file_spec_ptr->Dump(strm.AsRawOstream());
1315 return;
1316 }
1317 }
1318 // Keep the width spacing correct if things go wrong...
1319 if (width > 0)
1320 strm.Printf("%-*s", width, "");
1321}
1322
1323static void DumpDirectory(Stream &strm, const FileSpec *file_spec_ptr,
1324 uint32_t width) {
1325 if (file_spec_ptr) {
1326 if (width > 0)
1327 strm.Printf("%-*s", width, file_spec_ptr->GetDirectory().AsCString(""));
1328 else
1329 file_spec_ptr->GetDirectory().Dump(&strm);
1330 return;
1331 }
1332 // Keep the width spacing correct if things go wrong...
1333 if (width > 0)
1334 strm.Printf("%-*s", width, "");
1335}
1336
1337static void DumpBasename(Stream &strm, const FileSpec *file_spec_ptr,
1338 uint32_t width) {
1339 if (file_spec_ptr) {
1340 if (width > 0)
1341 strm.Printf("%-*s", width, file_spec_ptr->GetFilename().AsCString(""));
1342 else
1343 file_spec_ptr->GetFilename().Dump(&strm);
1344 return;
1345 }
1346 // Keep the width spacing correct if things go wrong...
1347 if (width > 0)
1348 strm.Printf("%-*s", width, "");
1349}
1350
1351static size_t DumpModuleObjfileHeaders(Stream &strm, ModuleList &module_list) {
1352 std::lock_guard<std::recursive_mutex> guard(module_list.GetMutex());
1353 const size_t num_modules = module_list.GetSize();
1354 if (num_modules == 0)
1355 return 0;
1356
1357 size_t num_dumped = 0;
1358 strm.Format("Dumping headers for {0} module(s).\n", num_modules);
1359 strm.IndentMore();
1360 for (ModuleSP module_sp : module_list.ModulesNoLocking()) {
1361 if (module_sp) {
1362 if (num_dumped++ > 0) {
1363 strm.EOL();
1364 strm.EOL();
1365 }
1366 ObjectFile *objfile = module_sp->GetObjectFile();
1367 if (objfile)
1368 objfile->Dump(&strm);
1369 else {
1370 strm.Format("No object file for module: {0:F}\n",
1371 module_sp->GetFileSpec());
1372 }
1373 }
1374 }
1375 strm.IndentLess();
1376 return num_dumped;
1377}
1378
1379static void DumpModuleSymtab(CommandInterpreter &interpreter, Stream &strm,
1380 Module *module, SortOrder sort_order,
1381 Mangled::NamePreference name_preference) {
1382 if (!module)
1383 return;
1384 if (Symtab *symtab = module->GetSymtab())
1385 symtab->Dump(&strm, interpreter.GetExecutionContext().GetTargetPtr(),
1386 sort_order, name_preference);
1387}
1388
1389static void DumpModuleSections(CommandInterpreter &interpreter, Stream &strm,
1390 Module *module) {
1391 if (module) {
1392 SectionList *section_list = module->GetSectionList();
1393 if (section_list) {
1394 strm.Printf("Sections for '%s' (%s):\n",
1395 module->GetSpecificationDescription().c_str(),
1397 section_list->Dump(strm.AsRawOstream(), strm.GetIndentLevel() + 2,
1398 interpreter.GetExecutionContext().GetTargetPtr(), true,
1399 UINT32_MAX);
1400 }
1401 }
1402}
1403
1404static bool DumpModuleSymbolFile(Stream &strm, Module *module) {
1405 if (module) {
1406 if (SymbolFile *symbol_file = module->GetSymbolFile(true)) {
1407 symbol_file->Dump(strm);
1408 return true;
1409 }
1410 }
1411 return false;
1412}
1413
1415 Module *module, bool errors_only,
1416 bool load_all_debug_info) {
1417 if (module) {
1418 if (SymbolFile *symbol_file = module->GetSymbolFile(/*can_create=*/true)) {
1420 if (symbol_file->GetSeparateDebugInfo(d, errors_only,
1421 load_all_debug_info)) {
1422 list.AddItem(
1423 std::make_shared<StructuredData::Dictionary>(std::move(d)));
1424 return true;
1425 }
1426 }
1427 }
1428 return false;
1429}
1430
1431static void DumpDwoFilesTable(Stream &strm,
1432 StructuredData::Array &dwo_listings) {
1433 strm.PutCString("Dwo ID Err Dwo Path");
1434 strm.EOL();
1435 strm.PutCString(
1436 "------------------ --- -----------------------------------------");
1437 strm.EOL();
1438 dwo_listings.ForEach([&strm](StructuredData::Object *dwo) {
1440 if (!dict)
1441 return false;
1442
1443 uint64_t dwo_id;
1444 if (dict->GetValueForKeyAsInteger("dwo_id", dwo_id))
1445 strm.Printf("0x%16.16" PRIx64 " ", dwo_id);
1446 else
1447 strm.Printf("0x???????????????? ");
1448
1449 llvm::StringRef error;
1450 if (dict->GetValueForKeyAsString("error", error))
1451 strm << "E " << error;
1452 else {
1453 llvm::StringRef resolved_dwo_path;
1454 if (dict->GetValueForKeyAsString("resolved_dwo_path",
1455 resolved_dwo_path)) {
1456 strm << " " << resolved_dwo_path;
1457 if (resolved_dwo_path.ends_with(".dwp")) {
1458 llvm::StringRef dwo_name;
1459 if (dict->GetValueForKeyAsString("dwo_name", dwo_name))
1460 strm << "(" << dwo_name << ")";
1461 }
1462 }
1463 }
1464 strm.EOL();
1465 return true;
1466 });
1467}
1468
1469static void DumpOsoFilesTable(Stream &strm,
1470 StructuredData::Array &oso_listings) {
1471 strm.PutCString("Mod Time Err Oso Path");
1472 strm.EOL();
1473 strm.PutCString("------------------ --- ---------------------");
1474 strm.EOL();
1475 oso_listings.ForEach([&strm](StructuredData::Object *oso) {
1477 if (!dict)
1478 return false;
1479
1480 uint32_t oso_mod_time;
1481 if (dict->GetValueForKeyAsInteger("oso_mod_time", oso_mod_time))
1482 strm.Printf("0x%16.16" PRIx32 " ", oso_mod_time);
1483
1484 llvm::StringRef error;
1485 if (dict->GetValueForKeyAsString("error", error))
1486 strm << "E " << error;
1487 else {
1488 llvm::StringRef oso_path;
1489 if (dict->GetValueForKeyAsString("oso_path", oso_path))
1490 strm << " " << oso_path;
1491 }
1492 strm.EOL();
1493 return true;
1494 });
1495}
1496
1497static void
1498DumpAddress(ExecutionContextScope *exe_scope, const Address &so_addr,
1499 bool verbose, bool all_ranges, Stream &strm,
1500 std::optional<Stream::HighlightSettings> settings = std::nullopt) {
1501 strm.IndentMore();
1502 strm.Indent(" Address: ");
1503 so_addr.Dump(&strm, exe_scope, Address::DumpStyleModuleWithFileAddress);
1504 strm.PutCString(" (");
1505 so_addr.Dump(&strm, exe_scope, Address::DumpStyleSectionNameOffset);
1506 strm.PutCString(")\n");
1507 strm.Indent(" Summary: ");
1508 const uint32_t save_indent = strm.GetIndentLevel();
1509 strm.SetIndentLevel(save_indent + 13);
1510 so_addr.Dump(&strm, exe_scope, Address::DumpStyleResolvedDescription,
1511 Address::DumpStyleInvalid, UINT32_MAX, false, settings);
1512 strm.SetIndentLevel(save_indent);
1513 // Print out detailed address information when verbose is enabled
1514 if (verbose) {
1515 strm.EOL();
1516 so_addr.Dump(&strm, exe_scope, Address::DumpStyleDetailedSymbolContext,
1517 Address::DumpStyleInvalid, UINT32_MAX, all_ranges, settings);
1518 }
1519 strm.IndentLess();
1520}
1521
1522static bool LookupAddressInModule(CommandInterpreter &interpreter, Stream &strm,
1523 Module *module, uint32_t resolve_mask,
1524 lldb::addr_t raw_addr, lldb::addr_t offset,
1525 bool verbose, bool all_ranges) {
1526 if (module) {
1527 lldb::addr_t addr = raw_addr - offset;
1528 Address so_addr;
1529 SymbolContext sc;
1530 Target *target = interpreter.GetExecutionContext().GetTargetPtr();
1531 if (target && target->HasLoadedSections()) {
1532 if (!target->ResolveLoadAddress(addr, so_addr))
1533 return false;
1534 else if (so_addr.GetModule().get() != module)
1535 return false;
1536 } else {
1537 if (!module->ResolveFileAddress(addr, so_addr))
1538 return false;
1539 }
1540
1541 ExecutionContextScope *exe_scope =
1543 DumpAddress(exe_scope, so_addr, verbose, all_ranges, strm);
1544 return true;
1545 }
1546
1547 return false;
1548}
1549
1550static uint32_t LookupSymbolInModule(CommandInterpreter &interpreter,
1551 Stream &strm, Module *module,
1552 const char *name, bool name_is_regex,
1553 bool verbose, bool all_ranges) {
1554 if (!module)
1555 return 0;
1556
1557 Symtab *symtab = module->GetSymtab();
1558 if (!symtab)
1559 return 0;
1560
1561 SymbolContext sc;
1562 const bool use_color = interpreter.GetDebugger().GetUseColor();
1563 std::vector<uint32_t> match_indexes;
1564 ConstString symbol_name(name);
1565 uint32_t num_matches = 0;
1566 if (name_is_regex) {
1567 RegularExpression name_regexp(symbol_name.GetStringRef());
1568 num_matches = symtab->AppendSymbolIndexesMatchingRegExAndType(
1569 name_regexp, eSymbolTypeAny, match_indexes);
1570 } else {
1571 num_matches =
1572 symtab->AppendSymbolIndexesWithName(symbol_name, match_indexes);
1573 }
1574
1575 if (num_matches > 0) {
1576 strm.Indent();
1577 strm.Printf("%u symbols match %s'%s' in ", num_matches,
1578 name_is_regex ? "the regular expression " : "", name);
1579 DumpFullpath(strm, &module->GetFileSpec(), 0);
1580 strm.PutCString(":\n");
1581 strm.IndentMore();
1583 name, interpreter.GetDebugger().GetRegexMatchAnsiPrefix(),
1584 interpreter.GetDebugger().GetRegexMatchAnsiSuffix());
1585 for (uint32_t i = 0; i < num_matches; ++i) {
1586 Symbol *symbol = symtab->SymbolAtIndex(match_indexes[i]);
1587 if (symbol) {
1588 if (symbol->ValueIsAddress()) {
1591 symbol->GetAddressRef(), verbose, all_ranges, strm,
1592 use_color && name_is_regex
1593 ? std::optional<Stream::HighlightSettings>{settings}
1594 : std::nullopt);
1595 strm.EOL();
1596 } else {
1597 strm.IndentMore();
1598 strm.Indent(" Name: ");
1600 symbol->GetDisplayName().GetStringRef(),
1601 use_color && name_is_regex
1602 ? std::optional<Stream::HighlightSettings>{settings}
1603 : std::nullopt);
1604 strm.EOL();
1605 strm.Indent(" Value: ");
1606 strm.Printf("0x%16.16" PRIx64 "\n", symbol->GetRawValue());
1607 if (symbol->GetByteSizeIsValid()) {
1608 strm.Indent(" Size: ");
1609 strm.Printf("0x%16.16" PRIx64 "\n", symbol->GetByteSize());
1610 }
1611 strm.IndentLess();
1612 }
1613 }
1614 }
1615 strm.IndentLess();
1616 }
1617 return num_matches;
1618}
1619
1621 ExecutionContextScope *exe_scope, Stream &strm,
1622 const SymbolContextList &sc_list, bool verbose, bool all_ranges,
1623 std::optional<Stream::HighlightSettings> settings = std::nullopt) {
1624 strm.IndentMore();
1625 bool first_module = true;
1626 for (const SymbolContext &sc : sc_list) {
1627 if (!first_module)
1628 strm.EOL();
1629
1630 Address addr;
1631 if (sc.line_entry.IsValid())
1632 addr = sc.line_entry.range.GetBaseAddress();
1633 else if (sc.block && sc.block->GetContainingInlinedBlock())
1634 sc.block->GetContainingInlinedBlock()->GetStartAddress(addr);
1635 else
1636 addr = sc.GetFunctionOrSymbolAddress();
1637
1638 DumpAddress(exe_scope, addr, verbose, all_ranges, strm, settings);
1639 first_module = false;
1640 }
1641 strm.IndentLess();
1642}
1643
1645 Stream &strm, Module *module,
1646 const char *name, bool name_is_regex,
1647 const ModuleFunctionSearchOptions &options,
1648 bool verbose, bool all_ranges) {
1649 if (module && name && name[0]) {
1650 SymbolContextList sc_list;
1651 size_t num_matches = 0;
1652 if (name_is_regex) {
1653 RegularExpression function_name_regex((llvm::StringRef(name)));
1654 module->FindFunctions(function_name_regex, options, sc_list);
1655 } else {
1656 ConstString function_name(name);
1657 module->FindFunctions(function_name, CompilerDeclContext(),
1658 eFunctionNameTypeAuto, options, sc_list);
1659 }
1660 num_matches = sc_list.GetSize();
1661 if (num_matches) {
1662 strm.Indent();
1663 strm.Printf("%" PRIu64 " match%s found in ", (uint64_t)num_matches,
1664 num_matches > 1 ? "es" : "");
1665 DumpFullpath(strm, &module->GetFileSpec(), 0);
1666 strm.PutCString(":\n");
1669 strm, sc_list, verbose, all_ranges);
1670 }
1671 return num_matches;
1672 }
1673 return 0;
1674}
1675
1676static size_t LookupTypeInModule(Target *target,
1677 CommandInterpreter &interpreter, Stream &strm,
1678 Module *module, const char *name_cstr,
1679 bool name_is_regex) {
1680 if (module && name_cstr && name_cstr[0]) {
1681 TypeQuery query(name_cstr);
1682 TypeResults results;
1683 module->FindTypes(query, results);
1684
1685 TypeList type_list;
1686 SymbolContext sc;
1687 if (module)
1688 sc.module_sp = module->shared_from_this();
1689 // Sort the type results and put the results that matched in \a module
1690 // first if \a module was specified.
1691 sc.SortTypeList(results.GetTypeMap(), type_list);
1692 if (type_list.Empty())
1693 return 0;
1694
1695 const uint64_t num_matches = type_list.GetSize();
1696
1697 strm.Indent();
1698 strm.Printf("%" PRIu64 " match%s found in ", num_matches,
1699 num_matches > 1 ? "es" : "");
1700 DumpFullpath(strm, &module->GetFileSpec(), 0);
1701 strm.PutCString(":\n");
1702 for (TypeSP type_sp : type_list.Types()) {
1703 if (!type_sp)
1704 continue;
1705 // Resolve the clang type so that any forward references to types
1706 // that haven't yet been parsed will get parsed.
1707 type_sp->GetFullCompilerType();
1708 type_sp->GetDescription(&strm, eDescriptionLevelFull, true, target);
1709 // Print all typedef chains
1710 TypeSP typedef_type_sp(type_sp);
1711 TypeSP typedefed_type_sp(typedef_type_sp->GetTypedefType());
1712 while (typedefed_type_sp) {
1713 strm.EOL();
1714 strm.Printf(" typedef '%s': ",
1715 typedef_type_sp->GetName().GetCString());
1716 typedefed_type_sp->GetFullCompilerType();
1717 typedefed_type_sp->GetDescription(&strm, eDescriptionLevelFull, true,
1718 target);
1719 typedef_type_sp = typedefed_type_sp;
1720 typedefed_type_sp = typedef_type_sp->GetTypedefType();
1721 }
1722 strm.EOL();
1723 }
1724 return type_list.GetSize();
1725 }
1726 return 0;
1727}
1728
1729static size_t LookupTypeHere(Target *target, CommandInterpreter &interpreter,
1730 Stream &strm, Module &module,
1731 const char *name_cstr, bool name_is_regex) {
1732 TypeQuery query(name_cstr);
1733 TypeResults results;
1734 module.FindTypes(query, results);
1735 TypeList type_list;
1736 SymbolContext sc;
1737 sc.module_sp = module.shared_from_this();
1738 sc.SortTypeList(results.GetTypeMap(), type_list);
1739 if (type_list.Empty())
1740 return 0;
1741
1742 strm.Indent();
1743 strm.PutCString("Best match found in ");
1744 DumpFullpath(strm, &module.GetFileSpec(), 0);
1745 strm.PutCString(":\n");
1746
1747 TypeSP type_sp(type_list.GetTypeAtIndex(0));
1748 if (type_sp) {
1749 // Resolve the clang type so that any forward references to types that
1750 // haven't yet been parsed will get parsed.
1751 type_sp->GetFullCompilerType();
1752 type_sp->GetDescription(&strm, eDescriptionLevelFull, true, target);
1753 // Print all typedef chains.
1754 TypeSP typedef_type_sp(type_sp);
1755 TypeSP typedefed_type_sp(typedef_type_sp->GetTypedefType());
1756 while (typedefed_type_sp) {
1757 strm.EOL();
1758 strm.Printf(" typedef '%s': ",
1759 typedef_type_sp->GetName().GetCString());
1760 typedefed_type_sp->GetFullCompilerType();
1761 typedefed_type_sp->GetDescription(&strm, eDescriptionLevelFull, true,
1762 target);
1763 typedef_type_sp = typedefed_type_sp;
1764 typedefed_type_sp = typedef_type_sp->GetTypedefType();
1765 }
1766 }
1767 strm.EOL();
1768 return type_list.GetSize();
1769}
1770
1772 Stream &strm, Module *module,
1773 const FileSpec &file_spec,
1774 uint32_t line, bool check_inlines,
1775 bool verbose, bool all_ranges) {
1776 if (module && file_spec) {
1777 SymbolContextList sc_list;
1778 const uint32_t num_matches = module->ResolveSymbolContextsForFileSpec(
1779 file_spec, line, check_inlines, eSymbolContextEverything, sc_list);
1780 if (num_matches > 0) {
1781 strm.Indent();
1782 strm.Printf("%u match%s found in ", num_matches,
1783 num_matches > 1 ? "es" : "");
1784 strm << file_spec;
1785 if (line > 0)
1786 strm.Printf(":%u", line);
1787 strm << " in ";
1788 DumpFullpath(strm, &module->GetFileSpec(), 0);
1789 strm.PutCString(":\n");
1792 strm, sc_list, verbose, all_ranges);
1793 return num_matches;
1794 }
1795 }
1796 return 0;
1797}
1798
1799static size_t FindModulesByName(Target *target, const char *module_name,
1800 ModuleList &module_list,
1801 bool check_global_list) {
1802 FileSpec module_file_spec(module_name);
1803 ModuleSpec module_spec(module_file_spec);
1804
1805 const size_t initial_size = module_list.GetSize();
1806
1807 if (check_global_list) {
1808 // Check the global list
1809 std::lock_guard<std::recursive_mutex> guard(
1811 const size_t num_modules = Module::GetNumberAllocatedModules();
1812 ModuleSP module_sp;
1813 for (size_t image_idx = 0; image_idx < num_modules; ++image_idx) {
1814 Module *module = Module::GetAllocatedModuleAtIndex(image_idx);
1815
1816 if (module) {
1817 if (module->MatchesModuleSpec(module_spec)) {
1818 module_sp = module->shared_from_this();
1819 module_list.AppendIfNeeded(module_sp);
1820 }
1821 }
1822 }
1823 } else {
1824 if (target) {
1825 target->GetImages().FindModules(module_spec, module_list);
1826 const size_t num_matches = module_list.GetSize();
1827
1828 // Not found in our module list for our target, check the main shared
1829 // module list in case it is a extra file used somewhere else
1830 if (num_matches == 0) {
1831 module_spec.GetArchitecture() = target->GetArchitecture();
1832 ModuleList::FindSharedModules(module_spec, module_list);
1833 }
1834 } else {
1835 ModuleList::FindSharedModules(module_spec, module_list);
1836 }
1837 }
1838
1839 return module_list.GetSize() - initial_size;
1840}
1841
1842#pragma mark CommandObjectTargetModulesModuleAutoComplete
1843
1844// A base command object class that can auto complete with module file
1845// paths
1846
1848 : public CommandObjectParsed {
1849public:
1851 const char *name,
1852 const char *help,
1853 const char *syntax,
1854 uint32_t flags = 0)
1855 : CommandObjectParsed(interpreter, name, help, syntax, flags) {
1857 }
1858
1860
1861 void
1867};
1868
1869#pragma mark CommandObjectTargetModulesSourceFileAutoComplete
1870
1871// A base command object class that can auto complete with module source
1872// file paths
1873
1875 : public CommandObjectParsed {
1876public:
1878 CommandInterpreter &interpreter, const char *name, const char *help,
1879 const char *syntax, uint32_t flags)
1880 : CommandObjectParsed(interpreter, name, help, syntax, flags) {
1882 }
1883
1885
1886 void
1892};
1893
1894#pragma mark CommandObjectTargetModulesDumpObjfile
1895
1898public:
1901 interpreter, "target modules dump objfile",
1902 "Dump the object file headers from one or more target modules.",
1903 nullptr, eCommandRequiresTarget) {}
1904
1906
1907protected:
1908 void DoExecute(Args &command, CommandReturnObject &result) override {
1909 Target &target = GetTarget();
1910
1911 uint32_t addr_byte_size = target.GetArchitecture().GetAddressByteSize();
1912 result.GetOutputStream().SetAddressByteSize(addr_byte_size);
1913 result.GetErrorStream().SetAddressByteSize(addr_byte_size);
1914
1915 size_t num_dumped = 0;
1916 if (command.GetArgumentCount() == 0) {
1917 // Dump all headers for all modules images
1918 num_dumped = DumpModuleObjfileHeaders(result.GetOutputStream(),
1919 target.GetImages());
1920 if (num_dumped == 0) {
1921 result.AppendError("the target has no associated executable images");
1922 }
1923 } else {
1924 // Find the modules that match the basename or full path.
1925 ModuleList module_list;
1926 const char *arg_cstr;
1927 for (int arg_idx = 0;
1928 (arg_cstr = command.GetArgumentAtIndex(arg_idx)) != nullptr;
1929 ++arg_idx) {
1930 size_t num_matched =
1931 FindModulesByName(&target, arg_cstr, module_list, true);
1932 if (num_matched == 0) {
1934 "Unable to find an image that matches '%s'.\n", arg_cstr);
1935 }
1936 }
1937 // Dump all the modules we found.
1938 num_dumped =
1939 DumpModuleObjfileHeaders(result.GetOutputStream(), module_list);
1940 }
1941
1942 if (num_dumped > 0) {
1944 } else {
1945 result.AppendError("no matching executable images found");
1946 }
1947 }
1948};
1949
1950#define LLDB_OPTIONS_target_modules_dump_symtab
1951#include "CommandOptions.inc"
1952
1955public:
1958 interpreter, "target modules dump symtab",
1959 "Dump the symbol table from one or more target modules.", nullptr,
1960 eCommandRequiresTarget) {}
1961
1963
1964 Options *GetOptions() override { return &m_options; }
1965
1966 class CommandOptions : public Options {
1967 public:
1968 CommandOptions() = default;
1969
1970 ~CommandOptions() override = default;
1971
1972 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1973 ExecutionContext *execution_context) override {
1974 Status error;
1975 const int short_option = m_getopt_table[option_idx].val;
1976
1977 switch (short_option) {
1978 case 'm':
1979 m_prefer_mangled.SetCurrentValue(true);
1980 m_prefer_mangled.SetOptionWasSet();
1981 break;
1982
1983 case 's':
1985 option_arg, GetDefinitions()[option_idx].enum_values,
1987 break;
1988
1989 default:
1990 llvm_unreachable("Unimplemented option");
1991 }
1992 return error;
1993 }
1994
1995 void OptionParsingStarting(ExecutionContext *execution_context) override {
1997 m_prefer_mangled.Clear();
1998 }
1999
2000 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
2001 return llvm::ArrayRef(g_target_modules_dump_symtab_options);
2002 }
2003
2006 };
2007
2008protected:
2009 void DoExecute(Args &command, CommandReturnObject &result) override {
2010 Target &target = GetTarget();
2011 uint32_t num_dumped = 0;
2012 Mangled::NamePreference name_preference =
2013 (m_options.m_prefer_mangled ? Mangled::ePreferMangled
2015
2016 uint32_t addr_byte_size = target.GetArchitecture().GetAddressByteSize();
2017 result.GetOutputStream().SetAddressByteSize(addr_byte_size);
2018 result.GetErrorStream().SetAddressByteSize(addr_byte_size);
2019
2020 if (command.GetArgumentCount() == 0) {
2021 // Dump all sections for all modules images
2022 const ModuleList &module_list = target.GetImages();
2023 std::lock_guard<std::recursive_mutex> guard(module_list.GetMutex());
2024 const size_t num_modules = module_list.GetSize();
2025 if (num_modules > 0) {
2026 result.GetOutputStream().Format(
2027 "Dumping symbol table for {0} modules.\n", num_modules);
2028 for (ModuleSP module_sp : module_list.ModulesNoLocking()) {
2029 if (num_dumped > 0) {
2030 result.GetOutputStream().EOL();
2031 result.GetOutputStream().EOL();
2032 }
2034 "Interrupted in dump all symtabs with {0} "
2035 "of {1} dumped.", num_dumped, num_modules))
2036 break;
2037
2038 num_dumped++;
2040 module_sp.get(), m_options.m_sort_order,
2041 name_preference);
2042 }
2043 } else {
2044 result.AppendError("the target has no associated executable images");
2045 return;
2046 }
2047 } else {
2048 // Dump specified images (by basename or fullpath)
2049 const char *arg_cstr;
2050 for (int arg_idx = 0;
2051 (arg_cstr = command.GetArgumentAtIndex(arg_idx)) != nullptr;
2052 ++arg_idx) {
2053 ModuleList module_list;
2054 const size_t num_matches =
2055 FindModulesByName(&target, arg_cstr, module_list, true);
2056 if (num_matches > 0) {
2057 for (ModuleSP module_sp : module_list.Modules()) {
2058 if (module_sp) {
2059 if (num_dumped > 0) {
2060 result.GetOutputStream().EOL();
2061 result.GetOutputStream().EOL();
2062 }
2064 "Interrupted in dump symtab list with {0} of {1} dumped.",
2065 num_dumped, num_matches))
2066 break;
2067
2068 num_dumped++;
2070 module_sp.get(), m_options.m_sort_order,
2071 name_preference);
2072 }
2073 }
2074 } else
2076 "Unable to find an image that matches '%s'.\n", arg_cstr);
2077 }
2078 }
2079
2080 if (num_dumped > 0)
2082 else {
2083 result.AppendError("no matching executable images found");
2084 }
2085 }
2086
2088};
2089
2090#pragma mark CommandObjectTargetModulesDumpSections
2091
2092// Image section dumping command
2093
2096public:
2099 interpreter, "target modules dump sections",
2100 "Dump the sections from one or more target modules.",
2101 //"target modules dump sections [<file1> ...]")
2102 nullptr, eCommandRequiresTarget) {}
2103
2105
2106protected:
2107 void DoExecute(Args &command, CommandReturnObject &result) override {
2108 Target &target = GetTarget();
2109 uint32_t num_dumped = 0;
2110
2111 uint32_t addr_byte_size = target.GetArchitecture().GetAddressByteSize();
2112 result.GetOutputStream().SetAddressByteSize(addr_byte_size);
2113 result.GetErrorStream().SetAddressByteSize(addr_byte_size);
2114
2115 if (command.GetArgumentCount() == 0) {
2116 // Dump all sections for all modules images
2117 const size_t num_modules = target.GetImages().GetSize();
2118 if (num_modules == 0) {
2119 result.AppendError("the target has no associated executable images");
2120 return;
2121 }
2122
2123 result.GetOutputStream().Format("Dumping sections for {0} modules.\n",
2124 num_modules);
2125 for (size_t image_idx = 0; image_idx < num_modules; ++image_idx) {
2127 "Interrupted in dump all sections with {0} of {1} dumped",
2128 image_idx, num_modules))
2129 break;
2130
2131 num_dumped++;
2134 target.GetImages().GetModulePointerAtIndex(image_idx));
2135 }
2136 } else {
2137 // Dump specified images (by basename or fullpath)
2138 const char *arg_cstr;
2139 for (int arg_idx = 0;
2140 (arg_cstr = command.GetArgumentAtIndex(arg_idx)) != nullptr;
2141 ++arg_idx) {
2142 ModuleList module_list;
2143 const size_t num_matches =
2144 FindModulesByName(&target, arg_cstr, module_list, true);
2145 if (num_matches > 0) {
2146 for (size_t i = 0; i < num_matches; ++i) {
2148 "Interrupted in dump section list with {0} of {1} dumped.",
2149 i, num_matches))
2150 break;
2151
2152 Module *module = module_list.GetModulePointerAtIndex(i);
2153 if (module) {
2154 num_dumped++;
2156 module);
2157 }
2158 }
2159 } else {
2160 // Check the global list
2161 std::lock_guard<std::recursive_mutex> guard(
2163
2165 "Unable to find an image that matches '%s'.\n", arg_cstr);
2166 }
2167 }
2168 }
2169
2170 if (num_dumped > 0)
2172 else {
2173 result.AppendError("no matching executable images found");
2174 }
2175 }
2176};
2177
2179public:
2182 interpreter, "target modules dump pcm-info",
2183 "Dump information about the given clang module (pcm).") {
2184 // Take a single file argument.
2186 }
2187
2189
2190protected:
2191 void DoExecute(Args &command, CommandReturnObject &result) override {
2192 if (command.GetArgumentCount() != 1) {
2193 result.AppendErrorWithFormat("'%s' takes exactly one pcm path argument.",
2194 m_cmd_name.c_str());
2195 return;
2196 }
2197
2198 const char *pcm_path = command.GetArgumentAtIndex(0);
2199 const FileSpec pcm_file{pcm_path};
2200
2201 if (pcm_file.GetFileNameExtension() != ".pcm") {
2202 result.AppendError("file must have a .pcm extension");
2203 return;
2204 }
2205
2206 if (!FileSystem::Instance().Exists(pcm_file)) {
2207 result.AppendError("pcm file does not exist");
2208 return;
2209 }
2210
2211 const char *clang_args[] = {"clang", pcm_path};
2212 clang::CompilerInstance compiler(clang::createInvocation(clang_args));
2213 compiler.setVirtualFileSystem(
2214 FileSystem::Instance().GetVirtualFileSystem());
2215 compiler.createDiagnostics();
2216
2217 // Pass empty deleter to not attempt to free memory that was allocated
2218 // outside of the current scope, possibly statically.
2219 std::shared_ptr<llvm::raw_ostream> Out(
2220 &result.GetOutputStream().AsRawOstream(), [](llvm::raw_ostream *) {});
2221 clang::DumpModuleInfoAction dump_module_info(Out);
2222 // DumpModuleInfoAction requires ObjectFilePCHContainerReader.
2223 compiler.getPCHContainerOperations()->registerReader(
2224 std::make_unique<clang::ObjectFilePCHContainerReader>());
2225
2226 if (compiler.ExecuteAction(dump_module_info))
2228 }
2229};
2230
2231#pragma mark CommandObjectTargetModulesDumpClangAST
2232
2233// Clang AST dumping command
2234
2237public:
2240 interpreter, "target modules dump ast",
2241 "Dump the clang ast for a given module's symbol file.",
2242 "target modules dump ast [--filter <name>] [<file1> ...]",
2243 eCommandRequiresTarget),
2244 m_filter(LLDB_OPT_SET_1, false, "filter", 'f', 0, eArgTypeName,
2245 "Dump only the decls whose names contain the specified filter "
2246 "string.",
2247 /*default_value=*/"") {
2249 m_option_group.Finalize();
2250 }
2251
2252 Options *GetOptions() override { return &m_option_group; }
2253
2255
2258
2259protected:
2260 void DoExecute(Args &command, CommandReturnObject &result) override {
2261 Target &target = GetTarget();
2262
2263 const ModuleList &module_list = target.GetImages();
2264 const size_t num_modules = module_list.GetSize();
2265 if (num_modules == 0) {
2266 result.AppendError("the target has no associated executable images");
2267 return;
2268 }
2269
2270 llvm::StringRef filter = m_filter.GetOptionValue().GetCurrentValueAsRef();
2271
2272 if (command.GetArgumentCount() == 0) {
2273 // Dump all ASTs for all modules images
2274 result.GetOutputStream().Format("Dumping clang ast for {0} modules.\n",
2275 num_modules);
2276 for (ModuleSP module_sp : module_list.ModulesNoLocking()) {
2277 if (INTERRUPT_REQUESTED(GetDebugger(), "Interrupted dumping clang ast"))
2278 break;
2279 if (SymbolFile *sf = module_sp->GetSymbolFile())
2280 sf->DumpClangAST(result.GetOutputStream(), filter,
2281 GetCommandInterpreter().GetDebugger().GetUseColor());
2282 }
2284 return;
2285 }
2286
2287 // Dump specified ASTs (by basename or fullpath)
2288 for (const Args::ArgEntry &arg : command.entries()) {
2289 ModuleList module_list;
2290 const size_t num_matches =
2291 FindModulesByName(&target, arg.c_str(), module_list, true);
2292 if (num_matches == 0) {
2293 // Check the global list
2294 std::lock_guard<std::recursive_mutex> guard(
2296
2298 "Unable to find an image that matches '%s'.\n", arg.c_str());
2299 continue;
2300 }
2301
2302 for (size_t i = 0; i < num_matches; ++i) {
2304 "Interrupted in dump clang ast list with {0} of {1} dumped.",
2305 i, num_matches))
2306 break;
2307
2308 Module *m = module_list.GetModulePointerAtIndex(i);
2309 if (SymbolFile *sf = m->GetSymbolFile())
2310 sf->DumpClangAST(result.GetOutputStream(), filter,
2311 GetCommandInterpreter().GetDebugger().GetUseColor());
2312 }
2313 }
2315 }
2316};
2317
2318#pragma mark CommandObjectTargetModulesDumpSymfile
2319
2320// Image debug symbol dumping command
2321
2324public:
2327 interpreter, "target modules dump symfile",
2328 "Dump the debug symbol file for one or more target modules.",
2329 //"target modules dump symfile [<file1> ...]")
2330 nullptr, eCommandRequiresTarget) {}
2331
2333
2334protected:
2335 void DoExecute(Args &command, CommandReturnObject &result) override {
2336 Target &target = GetTarget();
2337 uint32_t num_dumped = 0;
2338
2339 uint32_t addr_byte_size = target.GetArchitecture().GetAddressByteSize();
2340 result.GetOutputStream().SetAddressByteSize(addr_byte_size);
2341 result.GetErrorStream().SetAddressByteSize(addr_byte_size);
2342
2343 if (command.GetArgumentCount() == 0) {
2344 // Dump all sections for all modules images
2345 const ModuleList &target_modules = target.GetImages();
2346 std::lock_guard<std::recursive_mutex> guard(target_modules.GetMutex());
2347 const size_t num_modules = target_modules.GetSize();
2348 if (num_modules == 0) {
2349 result.AppendError("the target has no associated executable images");
2350 return;
2351 }
2352 result.GetOutputStream().Format(
2353 "Dumping debug symbols for {0} modules.\n", num_modules);
2354 for (ModuleSP module_sp : target_modules.ModulesNoLocking()) {
2355 if (INTERRUPT_REQUESTED(GetDebugger(), "Interrupted in dumping all "
2356 "debug symbols with {0} of {1} modules dumped",
2357 num_dumped, num_modules))
2358 break;
2359
2360 if (DumpModuleSymbolFile(result.GetOutputStream(), module_sp.get()))
2361 num_dumped++;
2362 }
2363 } else {
2364 // Dump specified images (by basename or fullpath)
2365 const char *arg_cstr;
2366 for (int arg_idx = 0;
2367 (arg_cstr = command.GetArgumentAtIndex(arg_idx)) != nullptr;
2368 ++arg_idx) {
2369 ModuleList module_list;
2370 const size_t num_matches =
2371 FindModulesByName(&target, arg_cstr, module_list, true);
2372 if (num_matches > 0) {
2373 for (size_t i = 0; i < num_matches; ++i) {
2374 if (INTERRUPT_REQUESTED(GetDebugger(), "Interrupted dumping {0} "
2375 "of {1} requested modules",
2376 i, num_matches))
2377 break;
2378 Module *module = module_list.GetModulePointerAtIndex(i);
2379 if (module) {
2380 if (DumpModuleSymbolFile(result.GetOutputStream(), module))
2381 num_dumped++;
2382 }
2383 }
2384 } else
2386 "Unable to find an image that matches '%s'.\n", arg_cstr);
2387 }
2388 }
2389
2390 if (num_dumped > 0)
2392 else {
2393 result.AppendError("no matching executable images found");
2394 }
2395 }
2396};
2397
2398#pragma mark CommandObjectTargetModulesDumpLineTable
2399#define LLDB_OPTIONS_target_modules_dump
2400#include "CommandOptions.inc"
2401
2402// Image debug line table dumping command
2403
2406public:
2409 interpreter, "target modules dump line-table",
2410 "Dump the line table for one or more compilation units.", nullptr,
2411 eCommandRequiresTarget) {}
2412
2414
2415 Options *GetOptions() override { return &m_options; }
2416
2417protected:
2418 void DoExecute(Args &command, CommandReturnObject &result) override {
2419 Target *target = m_exe_ctx.GetTargetPtr();
2420 uint32_t total_num_dumped = 0;
2421
2422 uint32_t addr_byte_size = target->GetArchitecture().GetAddressByteSize();
2423 result.GetOutputStream().SetAddressByteSize(addr_byte_size);
2424 result.GetErrorStream().SetAddressByteSize(addr_byte_size);
2425
2426 if (command.GetArgumentCount() == 0) {
2427 result.AppendError("file option must be specified");
2428 return;
2429 } else {
2430 // Dump specified images (by basename or fullpath)
2431 const char *arg_cstr;
2432 for (int arg_idx = 0;
2433 (arg_cstr = command.GetArgumentAtIndex(arg_idx)) != nullptr;
2434 ++arg_idx) {
2435 FileSpec file_spec(arg_cstr);
2436
2437 const ModuleList &target_modules = target->GetImages();
2438 std::lock_guard<std::recursive_mutex> guard(target_modules.GetMutex());
2439 size_t num_modules = target_modules.GetSize();
2440 if (num_modules > 0) {
2441 uint32_t num_dumped = 0;
2442 for (ModuleSP module_sp : target_modules.ModulesNoLocking()) {
2444 "Interrupted in dump all line tables with "
2445 "{0} of {1} dumped", num_dumped,
2446 num_modules))
2447 break;
2448
2450 m_interpreter, result.GetOutputStream(), module_sp.get(),
2451 file_spec,
2454 num_dumped++;
2455 }
2456 if (num_dumped == 0)
2458 "No source filenames matched '%s'.\n", arg_cstr);
2459 else
2460 total_num_dumped += num_dumped;
2461 }
2462 }
2463 }
2464
2465 if (total_num_dumped > 0)
2467 else {
2468 result.AppendError("no source filenames matched any command arguments");
2469 }
2470 }
2471
2472 class CommandOptions : public Options {
2473 public:
2475
2476 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
2477 ExecutionContext *execution_context) override {
2478 assert(option_idx == 0 && "We only have one option.");
2479 m_verbose = true;
2480
2481 return Status();
2482 }
2483
2484 void OptionParsingStarting(ExecutionContext *execution_context) override {
2485 m_verbose = false;
2486 }
2487
2488 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
2489 return llvm::ArrayRef(g_target_modules_dump_options);
2490 }
2491
2493 };
2494
2496};
2497
2498#pragma mark CommandObjectTargetModulesDumpSeparateDebugInfoFiles
2499#define LLDB_OPTIONS_target_modules_dump_separate_debug_info
2500#include "CommandOptions.inc"
2501
2502// Image debug separate debug info dumping command
2503
2506public:
2508 CommandInterpreter &interpreter)
2510 interpreter, "target modules dump separate-debug-info",
2511 "List the separate debug info symbol files for one or more target "
2512 "modules.",
2513 nullptr, eCommandRequiresTarget) {}
2514
2516
2517 Options *GetOptions() override { return &m_options; }
2518
2519 class CommandOptions : public Options {
2520 public:
2521 CommandOptions() = default;
2522
2523 ~CommandOptions() override = default;
2524
2525 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
2526 ExecutionContext *execution_context) override {
2527 Status error;
2528 const int short_option = m_getopt_table[option_idx].val;
2529
2530 switch (short_option) {
2531 case 'f':
2532 m_load_all_debug_info.SetCurrentValue(true);
2533 m_load_all_debug_info.SetOptionWasSet();
2534 break;
2535 case 'j':
2536 m_json.SetCurrentValue(true);
2537 m_json.SetOptionWasSet();
2538 break;
2539 case 'e':
2540 m_errors_only.SetCurrentValue(true);
2541 m_errors_only.SetOptionWasSet();
2542 break;
2543 default:
2544 llvm_unreachable("Unimplemented option");
2545 }
2546 return error;
2547 }
2548
2549 void OptionParsingStarting(ExecutionContext *execution_context) override {
2550 m_json.Clear();
2551 m_errors_only.Clear();
2552 m_load_all_debug_info.Clear();
2553 }
2554
2555 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
2556 return llvm::ArrayRef(g_target_modules_dump_separate_debug_info_options);
2557 }
2558
2562 };
2563
2564protected:
2565 void DoExecute(Args &command, CommandReturnObject &result) override {
2566 Target &target = GetTarget();
2567 uint32_t num_dumped = 0;
2568
2569 uint32_t addr_byte_size = target.GetArchitecture().GetAddressByteSize();
2570 result.GetOutputStream().SetAddressByteSize(addr_byte_size);
2571 result.GetErrorStream().SetAddressByteSize(addr_byte_size);
2572
2573 StructuredData::Array separate_debug_info_lists_by_module;
2574 if (command.GetArgumentCount() == 0) {
2575 // Dump all sections for all modules images
2576 const ModuleList &target_modules = target.GetImages();
2577 std::lock_guard<std::recursive_mutex> guard(target_modules.GetMutex());
2578 const size_t num_modules = target_modules.GetSize();
2579 if (num_modules == 0) {
2580 result.AppendError("the target has no associated executable images");
2581 return;
2582 }
2583 for (ModuleSP module_sp : target_modules.ModulesNoLocking()) {
2585 GetDebugger(),
2586 "Interrupted in dumping all "
2587 "separate debug info with {0} of {1} modules dumped",
2588 num_dumped, num_modules))
2589 break;
2590
2591 if (GetSeparateDebugInfoList(separate_debug_info_lists_by_module,
2592 module_sp.get(),
2593 bool(m_options.m_errors_only),
2594 bool(m_options.m_load_all_debug_info)))
2595 num_dumped++;
2596 }
2597 } else {
2598 // Dump specified images (by basename or fullpath)
2599 const char *arg_cstr;
2600 for (int arg_idx = 0;
2601 (arg_cstr = command.GetArgumentAtIndex(arg_idx)) != nullptr;
2602 ++arg_idx) {
2603 ModuleList module_list;
2604 const size_t num_matches =
2605 FindModulesByName(&target, arg_cstr, module_list, true);
2606 if (num_matches > 0) {
2607 for (size_t i = 0; i < num_matches; ++i) {
2609 "Interrupted dumping {0} "
2610 "of {1} requested modules",
2611 i, num_matches))
2612 break;
2613 Module *module = module_list.GetModulePointerAtIndex(i);
2614 if (GetSeparateDebugInfoList(separate_debug_info_lists_by_module,
2615 module, bool(m_options.m_errors_only),
2616 bool(m_options.m_load_all_debug_info)))
2617 num_dumped++;
2618 }
2619 } else
2621 "Unable to find an image that matches '%s'.\n", arg_cstr);
2622 }
2623 }
2624
2625 if (num_dumped > 0) {
2626 Stream &strm = result.GetOutputStream();
2627 // Display the debug info files in some format.
2628 if (m_options.m_json) {
2629 // JSON format
2630 separate_debug_info_lists_by_module.Dump(strm,
2631 /*pretty_print=*/true);
2632 } else {
2633 // Human-readable table format
2634 separate_debug_info_lists_by_module.ForEach(
2635 [&result, &strm](StructuredData::Object *obj) {
2636 if (!obj) {
2637 return false;
2638 }
2639
2640 // Each item in `separate_debug_info_lists_by_module` should be a
2641 // valid structured data dictionary.
2642 StructuredData::Dictionary *separate_debug_info_list =
2643 obj->GetAsDictionary();
2644 if (!separate_debug_info_list) {
2645 return false;
2646 }
2647
2648 llvm::StringRef type;
2649 llvm::StringRef symfile;
2650 StructuredData::Array *files;
2651 if (!(separate_debug_info_list->GetValueForKeyAsString("type",
2652 type) &&
2653 separate_debug_info_list->GetValueForKeyAsString("symfile",
2654 symfile) &&
2655 separate_debug_info_list->GetValueForKeyAsArray(
2656 "separate-debug-info-files", files))) {
2657 assert(false);
2658 }
2659
2660 strm << "Symbol file: " << symfile;
2661 strm.EOL();
2662 strm << "Type: \"" << type << "\"";
2663 strm.EOL();
2664 if (type == "dwo") {
2665 DumpDwoFilesTable(strm, *files);
2666 } else if (type == "oso") {
2667 DumpOsoFilesTable(strm, *files);
2668 } else {
2670 "Found unsupported debug info type '%s'.\n",
2671 type.str().c_str());
2672 }
2673 return true;
2674 });
2675 }
2677 } else {
2678 result.AppendError("no matching executable images found");
2679 }
2680 }
2681
2683};
2684
2685#pragma mark CommandObjectTargetModulesDump
2686
2687// Dump multi-word command for target modules
2688
2690public:
2691 // Constructors and Destructors
2694 interpreter, "target modules dump",
2695 "Commands for dumping information about one or more target "
2696 "modules.",
2697 "target modules dump "
2698 "[objfile|symtab|sections|ast|symfile|line-table|pcm-info|separate-"
2699 "debug-info] "
2700 "[<file1> <file2> ...]") {
2701 LoadSubCommand("objfile",
2703 new CommandObjectTargetModulesDumpObjfile(interpreter)));
2705 "symtab",
2707 LoadSubCommand("sections",
2709 interpreter)));
2710 LoadSubCommand("symfile",
2712 new CommandObjectTargetModulesDumpSymfile(interpreter)));
2714 "ast", CommandObjectSP(
2715 new CommandObjectTargetModulesDumpClangAST(interpreter)));
2716 LoadSubCommand("line-table",
2718 interpreter)));
2720 "pcm-info",
2723 LoadSubCommand("separate-debug-info",
2726 interpreter)));
2727 }
2728
2730};
2731
2733public:
2735 : CommandObjectParsed(interpreter, "target modules add",
2736 "Add a new module to the current target's modules.",
2737 "target modules add [<module>]",
2738 eCommandRequiresTarget),
2739 m_symbol_file(LLDB_OPT_SET_1, false, "symfile", 's', 0,
2741 "Fullpath to a stand alone debug "
2742 "symbols file for when debug symbols "
2743 "are not in the executable.") {
2747 m_option_group.Finalize();
2749 }
2750
2752
2753 Options *GetOptions() override { return &m_option_group; }
2754
2755protected:
2759
2760 void DoExecute(Args &args, CommandReturnObject &result) override {
2761 Target &target = GetTarget();
2762 bool flush = false;
2763
2764 const size_t argc = args.GetArgumentCount();
2765 if (argc == 0) {
2766 if (m_uuid_option_group.GetOptionValue().OptionWasSet()) {
2767 // We are given a UUID only, go locate the file
2768 ModuleSpec module_spec;
2769 module_spec.GetUUID() =
2770 m_uuid_option_group.GetOptionValue().GetCurrentValue();
2771 if (m_symbol_file.GetOptionValue().OptionWasSet())
2772 module_spec.GetSymbolFileSpec() =
2773 m_symbol_file.GetOptionValue().GetCurrentValue();
2774 Status error;
2776 ModuleSP module_sp(
2777 target.GetOrCreateModule(module_spec, true /* notify */));
2778 if (module_sp) {
2780 return;
2781 } else {
2782 StreamString strm;
2783 module_spec.GetUUID().Dump(strm);
2784 if (module_spec.GetFileSpec()) {
2785 if (module_spec.GetSymbolFileSpec()) {
2786 result.AppendErrorWithFormat(
2787 "Unable to create the executable or symbol file with "
2788 "UUID %s with path %s and symbol file %s",
2789 strm.GetData(), module_spec.GetFileSpec().GetPath().c_str(),
2790 module_spec.GetSymbolFileSpec().GetPath().c_str());
2791 } else {
2792 result.AppendErrorWithFormat(
2793 "Unable to create the executable or symbol file with "
2794 "UUID %s with path %s",
2795 strm.GetData(),
2796 module_spec.GetFileSpec().GetPath().c_str());
2797 }
2798 } else {
2799 result.AppendErrorWithFormat("Unable to create the executable "
2800 "or symbol file with UUID %s",
2801 strm.GetData());
2802 }
2803 return;
2804 }
2805 } else {
2806 StreamString strm;
2807 module_spec.GetUUID().Dump(strm);
2808 result.AppendErrorWithFormat(
2809 "Unable to locate the executable or symbol file with UUID %s",
2810 strm.GetData());
2811 result.SetError(std::move(error));
2812 return;
2813 }
2814 } else {
2815 result.AppendError(
2816 "one or more executable image paths must be specified");
2817 return;
2818 }
2819 } else {
2820 for (auto &entry : args.entries()) {
2821 if (entry.ref().empty())
2822 continue;
2823
2824 FileSpec file_spec(entry.ref());
2825 if (FileSystem::Instance().Exists(file_spec)) {
2826 ModuleSpec module_spec(file_spec);
2827 if (m_uuid_option_group.GetOptionValue().OptionWasSet())
2828 module_spec.GetUUID() =
2829 m_uuid_option_group.GetOptionValue().GetCurrentValue();
2830 if (m_symbol_file.GetOptionValue().OptionWasSet())
2831 module_spec.GetSymbolFileSpec() =
2832 m_symbol_file.GetOptionValue().GetCurrentValue();
2833 if (!module_spec.GetArchitecture().IsValid())
2834 module_spec.GetArchitecture() = target.GetArchitecture();
2835 Status error;
2836 ModuleSP module_sp(
2837 target.GetOrCreateModule(module_spec, true /* notify */, &error));
2838 if (!module_sp) {
2839 const char *error_cstr = error.AsCString();
2840 if (error_cstr)
2841 result.AppendError(error_cstr);
2842 else
2843 result.AppendErrorWithFormat("unsupported module: %s",
2844 entry.c_str());
2845 return;
2846 } else {
2847 flush = true;
2848 }
2850 } else {
2851 std::string resolved_path = file_spec.GetPath();
2852 if (resolved_path != entry.ref()) {
2853 result.AppendErrorWithFormat(
2854 "invalid module path '%s' with resolved path '%s'\n",
2855 entry.ref().str().c_str(), resolved_path.c_str());
2856 break;
2857 }
2858 result.AppendErrorWithFormat("invalid module path '%s'\n",
2859 entry.c_str());
2860 break;
2861 }
2862 }
2863 }
2864
2865 if (flush) {
2866 ProcessSP process = target.GetProcessSP();
2867 if (process)
2868 process->Flush();
2869 }
2870 }
2871};
2872
2875public:
2878 interpreter, "target modules load",
2879 "Set the load addresses for one or more sections in a target "
2880 "module.",
2881 "target modules load [--file <module> --uuid <uuid>] <sect-name> "
2882 "<address> [<sect-name> <address> ....]",
2883 eCommandRequiresTarget),
2884 m_file_option(LLDB_OPT_SET_1, false, "file", 'f', 0, eArgTypeName,
2885 "Fullpath or basename for module to load.", ""),
2886 m_load_option(LLDB_OPT_SET_1, false, "load", 'l',
2887 "Write file contents to the memory.", false, true),
2888 m_pc_option(LLDB_OPT_SET_1, false, "set-pc-to-entry", 'p',
2889 "Set PC to the entry point."
2890 " Only applicable with '--load' option.",
2891 false, true),
2892 m_slide_option(LLDB_OPT_SET_1, false, "slide", 's', 0, eArgTypeOffset,
2893 "Set the load address for all sections to be the "
2894 "virtual address in the file plus the offset.",
2895 0) {
2902 m_option_group.Finalize();
2903 }
2904
2906
2907 Options *GetOptions() override { return &m_option_group; }
2908
2909protected:
2910 void DoExecute(Args &args, CommandReturnObject &result) override {
2911 Target &target = GetTarget();
2912 const bool load = m_load_option.GetOptionValue().GetCurrentValue();
2913 const bool set_pc = m_pc_option.GetOptionValue().GetCurrentValue();
2914
2915 const size_t argc = args.GetArgumentCount();
2916 ModuleSpec module_spec;
2917 bool search_using_module_spec = false;
2918
2919 // Allow "load" option to work without --file or --uuid option.
2920 if (load) {
2921 if (!m_file_option.GetOptionValue().OptionWasSet() &&
2922 !m_uuid_option_group.GetOptionValue().OptionWasSet()) {
2923 ModuleList &module_list = target.GetImages();
2924 if (module_list.GetSize() == 1) {
2925 search_using_module_spec = true;
2926 module_spec.GetFileSpec() =
2927 module_list.GetModuleAtIndex(0)->GetFileSpec();
2928 }
2929 }
2930 }
2931
2932 if (m_file_option.GetOptionValue().OptionWasSet()) {
2933 search_using_module_spec = true;
2934 const char *arg_cstr = m_file_option.GetOptionValue().GetCurrentValue();
2935 const bool use_global_module_list = true;
2936 ModuleList module_list;
2937 const size_t num_matches = FindModulesByName(
2938 &target, arg_cstr, module_list, use_global_module_list);
2939 if (num_matches == 1) {
2940 module_spec.GetFileSpec() =
2941 module_list.GetModuleAtIndex(0)->GetFileSpec();
2942 } else if (num_matches > 1) {
2943 search_using_module_spec = false;
2944 result.AppendErrorWithFormat(
2945 "more than 1 module matched by name '%s'\n", arg_cstr);
2946 } else {
2947 search_using_module_spec = false;
2948 result.AppendErrorWithFormat("no object file for module '%s'\n",
2949 arg_cstr);
2950 }
2951 }
2952
2953 if (m_uuid_option_group.GetOptionValue().OptionWasSet()) {
2954 search_using_module_spec = true;
2955 module_spec.GetUUID() =
2956 m_uuid_option_group.GetOptionValue().GetCurrentValue();
2957 }
2958
2959 if (search_using_module_spec) {
2960 ModuleList matching_modules;
2961 target.GetImages().FindModules(module_spec, matching_modules);
2962 const size_t num_matches = matching_modules.GetSize();
2963
2964 char path[PATH_MAX];
2965 if (num_matches == 1) {
2966 Module *module = matching_modules.GetModulePointerAtIndex(0);
2967 if (module) {
2968 ObjectFile *objfile = module->GetObjectFile();
2969 if (objfile) {
2970 SectionList *section_list = module->GetSectionList();
2971 if (section_list) {
2972 bool changed = false;
2973 if (argc == 0) {
2974 if (m_slide_option.GetOptionValue().OptionWasSet()) {
2975 const addr_t slide =
2976 m_slide_option.GetOptionValue().GetCurrentValue();
2977 const bool slide_is_offset = true;
2978 module->SetLoadAddress(target, slide, slide_is_offset,
2979 changed);
2980 } else {
2981 result.AppendError("one or more section name + load "
2982 "address pair must be specified");
2983 return;
2984 }
2985 } else {
2986 if (m_slide_option.GetOptionValue().OptionWasSet()) {
2987 result.AppendError("The \"--slide <offset>\" option can't "
2988 "be used in conjunction with setting "
2989 "section load addresses.\n");
2990 return;
2991 }
2992
2993 for (size_t i = 0; i < argc; i += 2) {
2994 const char *sect_name = args.GetArgumentAtIndex(i);
2995 const char *load_addr_cstr = args.GetArgumentAtIndex(i + 1);
2996 if (sect_name && load_addr_cstr) {
2997 ConstString const_sect_name(sect_name);
2998 addr_t load_addr;
2999 if (llvm::to_integer(load_addr_cstr, load_addr)) {
3000 SectionSP section_sp(
3001 section_list->FindSectionByName(const_sect_name));
3002 if (section_sp) {
3003 if (section_sp->IsThreadSpecific()) {
3004 result.AppendErrorWithFormat(
3005 "thread specific sections are not yet "
3006 "supported (section '%s')\n",
3007 sect_name);
3008 break;
3009 } else {
3010 if (target.SetSectionLoadAddress(section_sp,
3011 load_addr))
3012 changed = true;
3014 "section '%s' loaded at 0x%" PRIx64 "\n",
3015 sect_name, load_addr);
3016 }
3017 } else {
3018 result.AppendErrorWithFormat("no section found that "
3019 "matches the section "
3020 "name '%s'\n",
3021 sect_name);
3022 break;
3023 }
3024 } else {
3025 result.AppendErrorWithFormat(
3026 "invalid load address string '%s'\n", load_addr_cstr);
3027 break;
3028 }
3029 } else {
3030 if (sect_name)
3031 result.AppendError("section names must be followed by "
3032 "a load address.\n");
3033 else
3034 result.AppendError("one or more section name + load "
3035 "address pair must be specified.\n");
3036 break;
3037 }
3038 }
3039 }
3040
3041 if (changed) {
3042 target.ModulesDidLoad(matching_modules);
3043 Process *process = m_exe_ctx.GetProcessPtr();
3044 if (process)
3045 process->Flush();
3046 }
3047 if (load) {
3048 ProcessSP process = target.CalculateProcess();
3049 Address file_entry = objfile->GetEntryPointAddress();
3050 if (!process) {
3051 result.AppendError("No process");
3052 return;
3053 }
3054 if (set_pc && !file_entry.IsValid()) {
3055 result.AppendError("No entry address in object file");
3056 return;
3057 }
3058 std::vector<ObjectFile::LoadableData> loadables(
3059 objfile->GetLoadableData(target));
3060 if (loadables.size() == 0) {
3061 result.AppendError("No loadable sections");
3062 return;
3063 }
3064 Status error = process->WriteObjectFile(std::move(loadables));
3065 if (error.Fail()) {
3066 result.AppendError(error.AsCString());
3067 return;
3068 }
3069 if (set_pc) {
3070 ThreadList &thread_list = process->GetThreadList();
3071 RegisterContextSP reg_context(
3072 thread_list.GetSelectedThread()->GetRegisterContext());
3073 addr_t file_entry_addr = file_entry.GetLoadAddress(&target);
3074 if (!reg_context->SetPC(file_entry_addr)) {
3075 result.AppendErrorWithFormat("failed to set PC value to "
3076 "0x%" PRIx64 "\n",
3077 file_entry_addr);
3078 }
3079 }
3080 }
3081 } else {
3082 module->GetFileSpec().GetPath(path, sizeof(path));
3083 result.AppendErrorWithFormat("no sections in object file '%s'\n",
3084 path);
3085 }
3086 } else {
3087 module->GetFileSpec().GetPath(path, sizeof(path));
3088 result.AppendErrorWithFormat("no object file for module '%s'\n",
3089 path);
3090 }
3091 } else {
3092 FileSpec *module_spec_file = module_spec.GetFileSpecPtr();
3093 if (module_spec_file) {
3094 module_spec_file->GetPath(path, sizeof(path));
3095 result.AppendErrorWithFormat("invalid module '%s'.\n", path);
3096 } else
3097 result.AppendError("no module spec");
3098 }
3099 } else {
3100 std::string uuid_str;
3101
3102 if (module_spec.GetFileSpec())
3103 module_spec.GetFileSpec().GetPath(path, sizeof(path));
3104 else
3105 path[0] = '\0';
3106
3107 if (module_spec.GetUUIDPtr())
3108 uuid_str = module_spec.GetUUID().GetAsString();
3109 if (num_matches > 1) {
3110 result.AppendErrorWithFormat(
3111 "multiple modules match%s%s%s%s:\n", path[0] ? " file=" : "",
3112 path, !uuid_str.empty() ? " uuid=" : "", uuid_str.c_str());
3113 for (size_t i = 0; i < num_matches; ++i) {
3114 if (matching_modules.GetModulePointerAtIndex(i)
3115 ->GetFileSpec()
3116 .GetPath(path, sizeof(path)))
3117 result.AppendMessageWithFormat("%s\n", path);
3118 }
3119 } else {
3120 result.AppendErrorWithFormat(
3121 "no modules were found that match%s%s%s%s.\n",
3122 path[0] ? " file=" : "", path, !uuid_str.empty() ? " uuid=" : "",
3123 uuid_str.c_str());
3124 }
3125 }
3126 } else {
3127 result.AppendError("either the \"--file <module>\" or the \"--uuid "
3128 "<uuid>\" option must be specified.\n");
3129 }
3130 }
3131
3138};
3139
3140#pragma mark CommandObjectTargetModulesList
3141// List images with associated information
3142#define LLDB_OPTIONS_target_modules_list
3143#include "CommandOptions.inc"
3144
3146public:
3147 class CommandOptions : public Options {
3148 public:
3149 CommandOptions() = default;
3150
3151 ~CommandOptions() override = default;
3152
3153 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
3154 ExecutionContext *execution_context) override {
3155 Status error;
3156
3157 const int short_option = m_getopt_table[option_idx].val;
3158 if (short_option == 'g') {
3160 } else if (short_option == 'a') {
3162 execution_context, option_arg, LLDB_INVALID_ADDRESS, &error);
3163 } else {
3164 unsigned long width = 0;
3165 option_arg.getAsInteger(0, width);
3166 m_format_array.push_back(std::make_pair(short_option, width));
3167 }
3168 return error;
3169 }
3170
3171 void OptionParsingStarting(ExecutionContext *execution_context) override {
3172 m_format_array.clear();
3175 }
3176
3177 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
3178 return llvm::ArrayRef(g_target_modules_list_options);
3179 }
3180
3181 // Instance variables to hold the values for command options.
3182 typedef std::vector<std::pair<char, uint32_t>> FormatWidthCollection;
3186 };
3187
3190 interpreter, "target modules list",
3191 "List current executable and dependent shared library images.") {
3193 }
3194
3196
3197 Options *GetOptions() override { return &m_options; }
3198
3199protected:
3200 void DoExecute(Args &command, CommandReturnObject &result) override {
3201 Target &target = GetTarget();
3202 const bool use_global_module_list = m_options.m_use_global_module_list;
3203 // Define a local module list here to ensure it lives longer than any
3204 // "locker" object which might lock its contents below (through the
3205 // "module_list_ptr" variable).
3206 ModuleList module_list;
3207 uint32_t addr_byte_size = target.GetArchitecture().GetAddressByteSize();
3208 result.GetOutputStream().SetAddressByteSize(addr_byte_size);
3209 result.GetErrorStream().SetAddressByteSize(addr_byte_size);
3210 // Dump all sections for all modules images
3211 Stream &strm = result.GetOutputStream();
3212
3213 if (m_options.m_module_addr != LLDB_INVALID_ADDRESS) {
3214 Address module_address;
3215 if (module_address.SetLoadAddress(m_options.m_module_addr, &target)) {
3216 ModuleSP module_sp(module_address.GetModule());
3217 if (module_sp) {
3218 PrintModule(target, module_sp.get(), 0, strm);
3220 } else {
3221 result.AppendErrorWithFormat(
3222 "Couldn't find module matching address: 0x%" PRIx64 ".",
3223 m_options.m_module_addr);
3224 }
3225 } else {
3226 result.AppendErrorWithFormat(
3227 "Couldn't find module containing address: 0x%" PRIx64 ".",
3228 m_options.m_module_addr);
3229 }
3230 return;
3231 }
3232
3233 size_t num_modules = 0;
3234
3235 // This locker will be locked on the mutex in module_list_ptr if it is
3236 // non-nullptr. Otherwise it will lock the
3237 // AllocationModuleCollectionMutex when accessing the global module list
3238 // directly.
3239 std::unique_lock<std::recursive_mutex> guard(
3241
3242 const ModuleList *module_list_ptr = nullptr;
3243 const size_t argc = command.GetArgumentCount();
3244 if (argc == 0) {
3245 if (use_global_module_list) {
3246 guard.lock();
3247 num_modules = Module::GetNumberAllocatedModules();
3248 } else {
3249 module_list_ptr = &target.GetImages();
3250 }
3251 } else {
3252 for (const Args::ArgEntry &arg : command) {
3253 // Dump specified images (by basename or fullpath)
3254 const size_t num_matches = FindModulesByName(
3255 &target, arg.c_str(), module_list, use_global_module_list);
3256 if (num_matches == 0) {
3257 if (argc == 1) {
3258 result.AppendErrorWithFormat("no modules found that match '%s'",
3259 arg.c_str());
3260 return;
3261 }
3262 }
3263 }
3264
3265 module_list_ptr = &module_list;
3266 }
3267
3268 std::unique_lock<std::recursive_mutex> lock;
3269 if (module_list_ptr != nullptr) {
3270 lock =
3271 std::unique_lock<std::recursive_mutex>(module_list_ptr->GetMutex());
3272
3273 num_modules = module_list_ptr->GetSize();
3274 }
3275
3276 if (num_modules > 0) {
3277 for (uint32_t image_idx = 0; image_idx < num_modules; ++image_idx) {
3278 ModuleSP module_sp;
3279 Module *module;
3280 if (module_list_ptr) {
3281 module_sp = module_list_ptr->GetModuleAtIndexUnlocked(image_idx);
3282 module = module_sp.get();
3283 } else {
3284 module = Module::GetAllocatedModuleAtIndex(image_idx);
3285 module_sp = module->shared_from_this();
3286 }
3287
3288 const size_t indent = strm.Printf("[%3u] ", image_idx);
3289 PrintModule(target, module, indent, strm);
3290 }
3292 } else {
3293 if (argc) {
3294 if (use_global_module_list)
3295 result.AppendError(
3296 "the global module list has no matching modules");
3297 else
3298 result.AppendError("the target has no matching modules");
3299 } else {
3300 if (use_global_module_list)
3301 result.AppendError("the global module list is empty");
3302 else
3303 result.AppendError(
3304 "the target has no associated executable images");
3305 }
3306 return;
3307 }
3308 }
3309
3310 void PrintModule(Target &target, Module *module, int indent, Stream &strm) {
3311 if (module == nullptr) {
3312 strm.PutCString("Null module");
3313 return;
3314 }
3315
3316 bool dump_object_name = false;
3317 if (m_options.m_format_array.empty()) {
3318 m_options.m_format_array.push_back(std::make_pair('u', 0));
3319 m_options.m_format_array.push_back(std::make_pair('h', 0));
3320 m_options.m_format_array.push_back(std::make_pair('f', 0));
3321 m_options.m_format_array.push_back(std::make_pair('S', 0));
3322 }
3323 const size_t num_entries = m_options.m_format_array.size();
3324 bool print_space = false;
3325 for (size_t i = 0; i < num_entries; ++i) {
3326 if (print_space)
3327 strm.PutChar(' ');
3328 print_space = true;
3329 const char format_char = m_options.m_format_array[i].first;
3330 uint32_t width = m_options.m_format_array[i].second;
3331 switch (format_char) {
3332 case 'A':
3333 DumpModuleArchitecture(strm, module, false, width);
3334 break;
3335
3336 case 't':
3337 DumpModuleArchitecture(strm, module, true, width);
3338 break;
3339
3340 case 'f':
3341 DumpFullpath(strm, &module->GetFileSpec(), width);
3342 dump_object_name = true;
3343 break;
3344
3345 case 'd':
3346 DumpDirectory(strm, &module->GetFileSpec(), width);
3347 break;
3348
3349 case 'b':
3350 DumpBasename(strm, &module->GetFileSpec(), width);
3351 dump_object_name = true;
3352 break;
3353
3354 case 'h':
3355 case 'o':
3356 // Image header address
3357 {
3358 uint32_t addr_nibble_width =
3359 target.GetArchitecture().GetAddressByteSize() * 2;
3360
3361 ObjectFile *objfile = module->GetObjectFile();
3362 if (objfile) {
3363 Address base_addr(objfile->GetBaseAddress());
3364 if (base_addr.IsValid()) {
3365 if (target.HasLoadedSections()) {
3366 lldb::addr_t load_addr = base_addr.GetLoadAddress(&target);
3367 if (load_addr == LLDB_INVALID_ADDRESS) {
3368 base_addr.Dump(&strm, &target,
3371 } else {
3372 if (format_char == 'o') {
3373 // Show the offset of slide for the image
3374 strm.Printf("0x%*.*" PRIx64, addr_nibble_width,
3375 addr_nibble_width,
3376 load_addr - base_addr.GetFileAddress());
3377 } else {
3378 // Show the load address of the image
3379 strm.Printf("0x%*.*" PRIx64, addr_nibble_width,
3380 addr_nibble_width, load_addr);
3381 }
3382 }
3383 break;
3384 }
3385 // The address was valid, but the image isn't loaded, output the
3386 // address in an appropriate format
3387 base_addr.Dump(&strm, &target, Address::DumpStyleFileAddress);
3388 break;
3389 }
3390 }
3391 strm.Printf("%*s", addr_nibble_width + 2, "");
3392 }
3393 break;
3394
3395 case 'r': {
3396 size_t ref_count = 0;
3397 char in_shared_cache = 'Y';
3398
3399 ModuleSP module_sp(module->shared_from_this());
3400 if (!ModuleList::ModuleIsInCache(module))
3401 in_shared_cache = 'N';
3402 if (module_sp) {
3403 // Take one away to make sure we don't count our local "module_sp"
3404 ref_count = module_sp.use_count() - 1;
3405 }
3406 if (width)
3407 strm.Printf("{%c %*" PRIu64 "}", in_shared_cache, width, (uint64_t)ref_count);
3408 else
3409 strm.Printf("{%c %" PRIu64 "}", in_shared_cache, (uint64_t)ref_count);
3410 } break;
3411
3412 case 's':
3413 case 'S': {
3414 if (const SymbolFile *symbol_file = module->GetSymbolFile()) {
3415 const FileSpec symfile_spec =
3416 symbol_file->GetObjectFile()->GetFileSpec();
3417 if (format_char == 'S') {
3418 // Dump symbol file only if different from module file
3419 if (!symfile_spec || symfile_spec == module->GetFileSpec()) {
3420 print_space = false;
3421 break;
3422 }
3423 // Add a newline and indent past the index
3424 strm.Printf("\n%*s", indent, "");
3425 }
3426 DumpFullpath(strm, &symfile_spec, width);
3427 dump_object_name = true;
3428 break;
3429 }
3430 strm.Printf("%.*s", width, "<NONE>");
3431 } break;
3432
3433 case 'm':
3434 strm.Format("{0:%c}", llvm::fmt_align(module->GetModificationTime(),
3435 llvm::AlignStyle::Left, width));
3436 break;
3437
3438 case 'p':
3439 strm.Printf("%p", static_cast<void *>(module));
3440 break;
3441
3442 case 'u':
3443 DumpModuleUUID(strm, module);
3444 break;
3445
3446 default:
3447 break;
3448 }
3449 }
3450 if (dump_object_name) {
3451 const char *object_name = module->GetObjectName().GetCString();
3452 if (object_name)
3453 strm.Printf("(%s)", object_name);
3454 }
3455 strm.EOL();
3456 }
3457
3459};
3460
3461#pragma mark CommandObjectTargetModulesShowUnwind
3462
3463// Lookup unwind information in images
3464#define LLDB_OPTIONS_target_modules_show_unwind
3465#include "CommandOptions.inc"
3466
3468public:
3469 enum {
3476 };
3477
3478 class CommandOptions : public Options {
3479 public:
3480 CommandOptions() = default;
3481
3482 ~CommandOptions() override = default;
3483
3484 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
3485 ExecutionContext *execution_context) override {
3486 Status error;
3487
3488 const int short_option = m_getopt_table[option_idx].val;
3489
3490 switch (short_option) {
3491 case 'a': {
3492 m_str = std::string(option_arg);
3494 m_addr = OptionArgParser::ToAddress(execution_context, option_arg,
3498 "invalid address string '%s'", option_arg.str().c_str());
3499 break;
3500 }
3501
3502 case 'n':
3503 m_str = std::string(option_arg);
3505 break;
3506
3507 case 'c':
3508 bool value, success;
3509 value = OptionArgParser::ToBoolean(option_arg, false, &success);
3510 if (success) {
3511 m_cached = value;
3512 } else {
3514 "invalid boolean value '%s' passed for -c option", option_arg);
3515 }
3516 break;
3517
3518 default:
3519 llvm_unreachable("Unimplemented option");
3520 }
3521
3522 return error;
3523 }
3524
3525 void OptionParsingStarting(ExecutionContext *execution_context) override {
3527 m_str.clear();
3529 m_cached = false;
3530 }
3531
3532 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
3533 return llvm::ArrayRef(g_target_modules_show_unwind_options);
3534 }
3535
3536 // Instance variables to hold the values for command options.
3537
3538 int m_type = eLookupTypeInvalid; // Should be a eLookupTypeXXX enum after
3539 // parsing options
3540 std::string m_str; // Holds name lookup
3541 lldb::addr_t m_addr = LLDB_INVALID_ADDRESS; // Holds the address to lookup
3542 bool m_cached = true;
3543 };
3544
3547 interpreter, "target modules show-unwind",
3548 "Show synthesized unwind instructions for a function.", nullptr,
3549 eCommandRequiresTarget | eCommandRequiresProcess |
3550 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused) {}
3551
3553
3554 Options *GetOptions() override { return &m_options; }
3555
3556protected:
3557 void DoExecute(Args &command, CommandReturnObject &result) override {
3558 Target *target = m_exe_ctx.GetTargetPtr();
3559 Process *process = m_exe_ctx.GetProcessPtr();
3560 ABI *abi = nullptr;
3561 if (process)
3562 abi = process->GetABI().get();
3563
3564 if (process == nullptr) {
3565 result.AppendError(
3566 "You must have a process running to use this command.");
3567 return;
3568 }
3569
3570 ThreadList threads(process->GetThreadList());
3571 if (threads.GetSize() == 0) {
3572 result.AppendError("the process must be paused to use this command");
3573 return;
3574 }
3575
3576 ThreadSP thread(threads.GetThreadAtIndex(0));
3577 if (!thread) {
3578 result.AppendError("the process must be paused to use this command");
3579 return;
3580 }
3581
3582 SymbolContextList sc_list;
3583
3584 if (m_options.m_type == eLookupTypeFunctionOrSymbol) {
3585 ConstString function_name(m_options.m_str.c_str());
3586 ModuleFunctionSearchOptions function_options;
3587 function_options.include_symbols = true;
3588 function_options.include_inlines = false;
3589 target->GetImages().FindFunctions(function_name, eFunctionNameTypeAuto,
3590 function_options, sc_list);
3591 } else if (m_options.m_type == eLookupTypeAddress && target) {
3592 Address addr;
3593 if (target->ResolveLoadAddress(m_options.m_addr, addr)) {
3594 SymbolContext sc;
3595 ModuleSP module_sp(addr.GetModule());
3596 module_sp->ResolveSymbolContextForAddress(addr,
3597 eSymbolContextEverything, sc);
3598 if (sc.function || sc.symbol) {
3599 sc_list.Append(sc);
3600 }
3601 }
3602 } else {
3603 result.AppendError(
3604 "address-expression or function name option must be specified.");
3605 return;
3606 }
3607
3608 if (sc_list.GetSize() == 0) {
3609 result.AppendErrorWithFormat("no unwind data found that matches '%s'.",
3610 m_options.m_str.c_str());
3611 return;
3612 }
3613
3614 for (const SymbolContext &sc : sc_list) {
3615 if (sc.symbol == nullptr && sc.function == nullptr)
3616 continue;
3617 if (!sc.module_sp || sc.module_sp->GetObjectFile() == nullptr)
3618 continue;
3619 Address addr = sc.GetFunctionOrSymbolAddress();
3620 if (!addr.IsValid())
3621 continue;
3622 ConstString funcname(sc.GetFunctionName());
3623 if (funcname.IsEmpty())
3624 continue;
3625 addr_t start_addr = addr.GetLoadAddress(target);
3626 if (abi)
3627 start_addr = abi->FixCodeAddress(start_addr);
3628
3629 UnwindTable &uw_table = sc.module_sp->GetUnwindTable();
3630 FuncUnwindersSP func_unwinders_sp =
3631 m_options.m_cached
3632 ? uw_table.GetFuncUnwindersContainingAddress(start_addr, sc)
3633 : uw_table.GetUncachedFuncUnwindersContainingAddress(start_addr,
3634 sc);
3635 if (!func_unwinders_sp)
3636 continue;
3637
3638 result.GetOutputStream().Printf(
3639 "UNWIND PLANS for %s`%s (start addr 0x%" PRIx64 ")\n",
3640 sc.module_sp->GetPlatformFileSpec().GetFilename().AsCString(),
3641 funcname.AsCString(), start_addr);
3642
3643 Args args;
3645 size_t count = args.GetArgumentCount();
3646 for (size_t i = 0; i < count; i++) {
3647 const char *trap_func_name = args.GetArgumentAtIndex(i);
3648 if (strcmp(funcname.GetCString(), trap_func_name) == 0)
3649 result.GetOutputStream().Printf(
3650 "This function is "
3651 "treated as a trap handler function via user setting.\n");
3652 }
3653 PlatformSP platform_sp(target->GetPlatform());
3654 if (platform_sp) {
3655 const std::vector<ConstString> trap_handler_names(
3656 platform_sp->GetTrapHandlerSymbolNames());
3657 for (ConstString trap_name : trap_handler_names) {
3658 if (trap_name == funcname) {
3659 result.GetOutputStream().Printf(
3660 "This function's "
3661 "name is listed by the platform as a trap handler.\n");
3662 }
3663 }
3664 }
3665
3666 result.GetOutputStream().Printf("\n");
3667
3668 if (std::shared_ptr<const UnwindPlan> plan_sp =
3669 func_unwinders_sp->GetUnwindPlanAtNonCallSite(*target, *thread)) {
3670 result.GetOutputStream().Printf(
3671 "Asynchronous (not restricted to call-sites) UnwindPlan is '%s'\n",
3672 plan_sp->GetSourceName().AsCString());
3673 }
3674 if (std::shared_ptr<const UnwindPlan> plan_sp =
3675 func_unwinders_sp->GetUnwindPlanAtCallSite(*target, *thread)) {
3676 result.GetOutputStream().Printf(
3677 "Synchronous (restricted to call-sites) UnwindPlan is '%s'\n",
3678 plan_sp->GetSourceName().AsCString());
3679 }
3680 if (std::shared_ptr<const UnwindPlan> plan_sp =
3681 func_unwinders_sp->GetUnwindPlanFastUnwind(*target, *thread)) {
3682 result.GetOutputStream().Printf("Fast UnwindPlan is '%s'\n",
3683 plan_sp->GetSourceName().AsCString());
3684 }
3685
3686 result.GetOutputStream().Printf("\n");
3687
3688 if (std::shared_ptr<const UnwindPlan> plan_sp =
3689 func_unwinders_sp->GetAssemblyUnwindPlan(*target, *thread)) {
3690 result.GetOutputStream().Printf(
3691 "Assembly language inspection UnwindPlan:\n");
3692 plan_sp->Dump(result.GetOutputStream(), thread.get(),
3694 result.GetOutputStream().Printf("\n");
3695 }
3696
3697 if (std::shared_ptr<const UnwindPlan> plan_sp =
3698 func_unwinders_sp->GetObjectFileUnwindPlan(*target)) {
3699 result.GetOutputStream().Printf("object file UnwindPlan:\n");
3700 plan_sp->Dump(result.GetOutputStream(), thread.get(),
3702 result.GetOutputStream().Printf("\n");
3703 }
3704
3705 if (std::shared_ptr<const UnwindPlan> plan_sp =
3706 func_unwinders_sp->GetObjectFileAugmentedUnwindPlan(*target,
3707 *thread)) {
3708 result.GetOutputStream().Printf("object file augmented UnwindPlan:\n");
3709 plan_sp->Dump(result.GetOutputStream(), thread.get(),
3711 result.GetOutputStream().Printf("\n");
3712 }
3713
3714 if (std::shared_ptr<const UnwindPlan> plan_sp =
3715 func_unwinders_sp->GetEHFrameUnwindPlan(*target)) {
3716 result.GetOutputStream().Printf("eh_frame UnwindPlan:\n");
3717 plan_sp->Dump(result.GetOutputStream(), thread.get(),
3719 result.GetOutputStream().Printf("\n");
3720 }
3721
3722 if (std::shared_ptr<const UnwindPlan> plan_sp =
3723 func_unwinders_sp->GetEHFrameAugmentedUnwindPlan(*target,
3724 *thread)) {
3725 result.GetOutputStream().Printf("eh_frame augmented UnwindPlan:\n");
3726 plan_sp->Dump(result.GetOutputStream(), thread.get(),
3728 result.GetOutputStream().Printf("\n");
3729 }
3730
3731 if (std::shared_ptr<const UnwindPlan> plan_sp =
3732 func_unwinders_sp->GetDebugFrameUnwindPlan(*target)) {
3733 result.GetOutputStream().Printf("debug_frame UnwindPlan:\n");
3734 plan_sp->Dump(result.GetOutputStream(), thread.get(),
3736 result.GetOutputStream().Printf("\n");
3737 }
3738
3739 if (std::shared_ptr<const UnwindPlan> plan_sp =
3740 func_unwinders_sp->GetDebugFrameAugmentedUnwindPlan(*target,
3741 *thread)) {
3742 result.GetOutputStream().Printf("debug_frame augmented UnwindPlan:\n");
3743 plan_sp->Dump(result.GetOutputStream(), thread.get(),
3745 result.GetOutputStream().Printf("\n");
3746 }
3747
3748 if (std::shared_ptr<const UnwindPlan> plan_sp =
3749 func_unwinders_sp->GetArmUnwindUnwindPlan(*target)) {
3750 result.GetOutputStream().Printf("ARM.exidx unwind UnwindPlan:\n");
3751 plan_sp->Dump(result.GetOutputStream(), thread.get(),
3753 result.GetOutputStream().Printf("\n");
3754 }
3755
3756 if (std::shared_ptr<const UnwindPlan> plan_sp =
3757 func_unwinders_sp->GetSymbolFileUnwindPlan(*thread)) {
3758 result.GetOutputStream().Printf("Symbol file UnwindPlan:\n");
3759 plan_sp->Dump(result.GetOutputStream(), thread.get(),
3761 result.GetOutputStream().Printf("\n");
3762 }
3763
3764 if (std::shared_ptr<const UnwindPlan> plan_sp =
3765 func_unwinders_sp->GetCompactUnwindUnwindPlan(*target)) {
3766 result.GetOutputStream().Printf("Compact unwind UnwindPlan:\n");
3767 plan_sp->Dump(result.GetOutputStream(), thread.get(),
3769 result.GetOutputStream().Printf("\n");
3770 }
3771
3772 if (std::shared_ptr<const UnwindPlan> plan_sp =
3773 func_unwinders_sp->GetUnwindPlanFastUnwind(*target, *thread)) {
3774 result.GetOutputStream().Printf("Fast UnwindPlan:\n");
3775 plan_sp->Dump(result.GetOutputStream(), thread.get(),
3777 result.GetOutputStream().Printf("\n");
3778 }
3779
3780 ABISP abi_sp = process->GetABI();
3781 if (abi_sp) {
3782 if (UnwindPlanSP plan_sp = abi_sp->CreateDefaultUnwindPlan()) {
3783 result.GetOutputStream().Printf("Arch default UnwindPlan:\n");
3784 plan_sp->Dump(result.GetOutputStream(), thread.get(),
3786 result.GetOutputStream().Printf("\n");
3787 }
3788
3789 if (UnwindPlanSP plan_sp = abi_sp->CreateFunctionEntryUnwindPlan()) {
3790 result.GetOutputStream().Printf(
3791 "Arch default at entry point UnwindPlan:\n");
3792 plan_sp->Dump(result.GetOutputStream(), thread.get(),
3794 result.GetOutputStream().Printf("\n");
3795 }
3796 }
3797
3798 result.GetOutputStream().Printf("\n");
3799 }
3800 }
3801
3803};
3804
3805// Lookup information in images
3806#define LLDB_OPTIONS_target_modules_lookup
3807#include "CommandOptions.inc"
3808
3810public:
3811 enum {
3815 eLookupTypeFileLine, // Line is optional
3820 };
3821
3822 class CommandOptions : public Options {
3823 public:
3825
3826 ~CommandOptions() override = default;
3827
3828 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
3829 ExecutionContext *execution_context) override {
3830 Status error;
3831
3832 const int short_option = m_getopt_table[option_idx].val;
3833
3834 switch (short_option) {
3835 case 'a': {
3837 m_addr = OptionArgParser::ToAddress(execution_context, option_arg,
3839 } break;
3840
3841 case 'o':
3842 if (option_arg.getAsInteger(0, m_offset))
3844 "invalid offset string '%s'", option_arg.str().c_str());
3845 break;
3846
3847 case 's':
3848 m_str = std::string(option_arg);
3850 break;
3851
3852 case 'f':
3853 m_file.SetFile(option_arg, FileSpec::Style::native);
3855 break;
3856
3857 case 'i':
3858 m_include_inlines = false;
3859 break;
3860
3861 case 'l':
3862 if (option_arg.getAsInteger(0, m_line_number))
3864 "invalid line number string '%s'", option_arg.str().c_str());
3865 else if (m_line_number == 0)
3866 error = Status::FromErrorString("zero is an invalid line number");
3868 break;
3869
3870 case 'F':
3871 m_str = std::string(option_arg);
3873 break;
3874
3875 case 'n':
3876 m_str = std::string(option_arg);
3878 break;
3879
3880 case 't':
3881 m_str = std::string(option_arg);
3883 break;
3884
3885 case 'v':
3886 m_verbose = true;
3887 break;
3888
3889 case 'A':
3890 m_print_all = true;
3891 break;
3892
3893 case 'r':
3894 m_use_regex = true;
3895 break;
3896
3897 case '\x01':
3898 m_all_ranges = true;
3899 break;
3900 default:
3901 llvm_unreachable("Unimplemented option");
3902 }
3903
3904 return error;
3905 }
3906
3907 void OptionParsingStarting(ExecutionContext *execution_context) override {
3909 m_str.clear();
3910 m_file.Clear();
3912 m_offset = 0;
3913 m_line_number = 0;
3914 m_use_regex = false;
3915 m_include_inlines = true;
3916 m_all_ranges = false;
3917 m_verbose = false;
3918 m_print_all = false;
3919 }
3920
3921 Status OptionParsingFinished(ExecutionContext *execution_context) override {
3922 Status status;
3923 if (m_all_ranges && !m_verbose) {
3924 status =
3925 Status::FromErrorString("--show-variable-ranges must be used in "
3926 "conjunction with --verbose.");
3927 }
3928 return status;
3929 }
3930
3931 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
3932 return llvm::ArrayRef(g_target_modules_lookup_options);
3933 }
3934
3935 int m_type; // Should be a eLookupTypeXXX enum after parsing options
3936 std::string m_str; // Holds name lookup
3937 FileSpec m_file; // Files for file lookups
3938 lldb::addr_t m_addr; // Holds the address to lookup
3940 m_offset; // Subtract this offset from m_addr before doing lookups.
3941 uint32_t m_line_number; // Line number for file+line lookups
3942 bool m_use_regex; // Name lookups in m_str are regular expressions.
3943 bool m_include_inlines; // Check for inline entries when looking up by
3944 // file/line.
3945 bool m_all_ranges; // Print all ranges or single range.
3946 bool m_verbose; // Enable verbose lookup info
3947 bool m_print_all; // Print all matches, even in cases where there's a best
3948 // match.
3949 };
3950
3952 : CommandObjectParsed(interpreter, "target modules lookup",
3953 "Look up information within executable and "
3954 "dependent shared library images.",
3955 nullptr, eCommandRequiresTarget) {
3957 }
3958
3960
3961 Options *GetOptions() override { return &m_options; }
3962
3964 bool &syntax_error) {
3965 switch (m_options.m_type) {
3966 case eLookupTypeAddress:
3970 case eLookupTypeSymbol:
3971 default:
3972 return false;
3973 case eLookupTypeType:
3974 break;
3975 }
3976
3977 StackFrameSP frame = m_exe_ctx.GetFrameSP();
3978
3979 if (!frame)
3980 return false;
3981
3982 const SymbolContext &sym_ctx(frame->GetSymbolContext(eSymbolContextModule));
3983
3984 if (!sym_ctx.module_sp)
3985 return false;
3986
3987 switch (m_options.m_type) {
3988 default:
3989 return false;
3990 case eLookupTypeType:
3991 if (!m_options.m_str.empty()) {
3993 result.GetOutputStream(), *sym_ctx.module_sp,
3994 m_options.m_str.c_str(), m_options.m_use_regex)) {
3996 return true;
3997 }
3998 }
3999 break;
4000 }
4001
4002 return false;
4003 }
4004
4005 bool LookupInModule(CommandInterpreter &interpreter, Module *module,
4006 CommandReturnObject &result, bool &syntax_error) {
4007 switch (m_options.m_type) {
4008 case eLookupTypeAddress:
4009 if (m_options.m_addr != LLDB_INVALID_ADDRESS) {
4011 m_interpreter, result.GetOutputStream(), module,
4012 eSymbolContextEverything |
4013 (m_options.m_verbose
4014 ? static_cast<int>(eSymbolContextVariable)
4015 : 0),
4016 m_options.m_addr, m_options.m_offset, m_options.m_verbose,
4017 m_options.m_all_ranges)) {
4019 return true;
4020 }
4021 }
4022 break;
4023
4024 case eLookupTypeSymbol:
4025 if (!m_options.m_str.empty()) {
4027 module, m_options.m_str.c_str(),
4028 m_options.m_use_regex, m_options.m_verbose,
4029 m_options.m_all_ranges)) {
4031 return true;
4032 }
4033 }
4034 break;
4035
4037 if (m_options.m_file) {
4039 m_interpreter, result.GetOutputStream(), module,
4040 m_options.m_file, m_options.m_line_number,
4041 m_options.m_include_inlines, m_options.m_verbose,
4042 m_options.m_all_ranges)) {
4044 return true;
4045 }
4046 }
4047 break;
4048
4051 if (!m_options.m_str.empty()) {
4052 ModuleFunctionSearchOptions function_options;
4053 function_options.include_symbols =
4055 function_options.include_inlines = m_options.m_include_inlines;
4056
4058 module, m_options.m_str.c_str(),
4059 m_options.m_use_regex, function_options,
4060 m_options.m_verbose,
4061 m_options.m_all_ranges)) {
4063 return true;
4064 }
4065 }
4066 break;
4067
4068 case eLookupTypeType:
4069 if (!m_options.m_str.empty()) {
4071 &GetTarget(), m_interpreter, result.GetOutputStream(), module,
4072 m_options.m_str.c_str(), m_options.m_use_regex)) {
4074 return true;
4075 }
4076 }
4077 break;
4078
4079 default:
4080 m_options.GenerateOptionUsage(
4081 result.GetErrorStream(), *this,
4082 GetCommandInterpreter().GetDebugger().GetTerminalWidth(),
4083 GetCommandInterpreter().GetDebugger().GetUseColor());
4084 syntax_error = true;
4085 break;
4086 }
4087
4089 return false;
4090 }
4091
4092protected:
4093 void DoExecute(Args &command, CommandReturnObject &result) override {
4094 Target &target = GetTarget();
4095 bool syntax_error = false;
4096 uint32_t i;
4097 uint32_t num_successful_lookups = 0;
4098 uint32_t addr_byte_size = target.GetArchitecture().GetAddressByteSize();
4099 result.GetOutputStream().SetAddressByteSize(addr_byte_size);
4100 result.GetErrorStream().SetAddressByteSize(addr_byte_size);
4101 // Dump all sections for all modules images
4102
4103 if (command.GetArgumentCount() == 0) {
4104 // Where it is possible to look in the current symbol context first,
4105 // try that. If this search was successful and --all was not passed,
4106 // don't print anything else.
4107 if (LookupHere(m_interpreter, result, syntax_error)) {
4108 result.GetOutputStream().EOL();
4109 num_successful_lookups++;
4110 if (!m_options.m_print_all) {
4112 return;
4113 }
4114 }
4115
4116 // Dump all sections for all other modules
4117
4118 const ModuleList &target_modules = target.GetImages();
4119 std::lock_guard<std::recursive_mutex> guard(target_modules.GetMutex());
4120 if (target_modules.GetSize() == 0) {
4121 result.AppendError("the target has no associated executable images");
4122 return;
4123 }
4124
4125 for (ModuleSP module_sp : target_modules.ModulesNoLocking()) {
4126 if (LookupInModule(m_interpreter, module_sp.get(), result,
4127 syntax_error)) {
4128 result.GetOutputStream().EOL();
4129 num_successful_lookups++;
4130 }
4131 }
4132 } else {
4133 // Dump specified images (by basename or fullpath)
4134 const char *arg_cstr;
4135 for (i = 0; (arg_cstr = command.GetArgumentAtIndex(i)) != nullptr &&
4136 !syntax_error;
4137 ++i) {
4138 ModuleList module_list;
4139 const size_t num_matches =
4140 FindModulesByName(&target, arg_cstr, module_list, false);
4141 if (num_matches > 0) {
4142 for (size_t j = 0; j < num_matches; ++j) {
4143 Module *module = module_list.GetModulePointerAtIndex(j);
4144 if (module) {
4145 if (LookupInModule(m_interpreter, module, result, syntax_error)) {
4146 result.GetOutputStream().EOL();
4147 num_successful_lookups++;
4148 }
4149 }
4150 }
4151 } else
4153 "Unable to find an image that matches '%s'.\n", arg_cstr);
4154 }
4155 }
4156
4157 if (num_successful_lookups > 0)
4159 else
4161 }
4162
4164};
4165
4166#pragma mark CommandObjectMultiwordImageSearchPaths
4167
4168// CommandObjectMultiwordImageSearchPaths
4169
4171 : public CommandObjectMultiword {
4172public:
4175 interpreter, "target modules search-paths",
4176 "Commands for managing module search paths for a target.",
4177 "target modules search-paths <subcommand> [<subcommand-options>]") {
4179 "add", CommandObjectSP(
4183 interpreter)));
4185 "insert",
4190 interpreter)));
4193 interpreter)));
4194 }
4195
4197};
4198
4199#pragma mark CommandObjectTargetModules
4200
4201// CommandObjectTargetModules
4202
4204public:
4205 // Constructors and Destructors
4207 : CommandObjectMultiword(interpreter, "target modules",
4208 "Commands for accessing information for one or "
4209 "more target modules.",
4210 "target modules <sub-command> ...") {
4212 "add", CommandObjectSP(new CommandObjectTargetModulesAdd(interpreter)));
4214 interpreter)));
4216 interpreter)));
4218 interpreter)));
4220 "lookup",
4223 "search-paths",
4227 "show-unwind",
4229 }
4230
4231 ~CommandObjectTargetModules() override = default;
4232
4233private:
4234 // For CommandObjectTargetModules only
4238};
4239
4241public:
4244 interpreter, "target symbols add",
4245 "Add a debug symbol file to one of the target's current modules by "
4246 "specifying a path to a debug symbols file or by using the options "
4247 "to specify a module.",
4248 "target symbols add <cmd-options> [<symfile>]",
4249 eCommandRequiresTarget),
4251 LLDB_OPT_SET_1, false, "shlib", 's', lldb::eModuleCompletion,
4253 "Locate the debug symbols for the shared library specified by "
4254 "name."),
4256 LLDB_OPT_SET_2, false, "frame", 'F',
4257 "Locate the debug symbols for the currently selected frame.", false,
4258 true),
4259 m_current_stack_option(LLDB_OPT_SET_2, false, "stack", 'S',
4260 "Locate the debug symbols for every frame in "
4261 "the current call stack.",
4262 false, true)
4263
4264 {
4272 m_option_group.Finalize();
4274 }
4275
4277
4278 Options *GetOptions() override { return &m_option_group; }
4279
4280protected:
4281 bool AddModuleSymbols(Target *target, ModuleSpec &module_spec, bool &flush,
4282 CommandReturnObject &result) {
4283 const FileSpec &symbol_fspec = module_spec.GetSymbolFileSpec();
4284 if (!symbol_fspec) {
4285 result.AppendError(
4286 "one or more executable image paths must be specified");
4287 return false;
4288 }
4289
4290 char symfile_path[PATH_MAX];
4291 symbol_fspec.GetPath(symfile_path, sizeof(symfile_path));
4292
4293 if (!module_spec.GetUUID().IsValid()) {
4294 if (!module_spec.GetFileSpec() && !module_spec.GetPlatformFileSpec())
4295 module_spec.GetFileSpec().SetFilename(symbol_fspec.GetFilename());
4296 }
4297
4298 // Now module_spec represents a symbol file for a module that might exist
4299 // in the current target. Let's find possible matches.
4300 ModuleList matching_modules;
4301
4302 // First extract all module specs from the symbol file
4303 lldb_private::ModuleSpecList symfile_module_specs;
4305 0, 0, symfile_module_specs)) {
4306 // Now extract the module spec that matches the target architecture
4307 ModuleSpec target_arch_module_spec;
4308 ModuleSpec symfile_module_spec;
4309 target_arch_module_spec.GetArchitecture() = target->GetArchitecture();
4310 if (symfile_module_specs.FindMatchingModuleSpec(target_arch_module_spec,
4311 symfile_module_spec)) {
4312 if (symfile_module_spec.GetUUID().IsValid()) {
4313 // It has a UUID, look for this UUID in the target modules
4314 ModuleSpec symfile_uuid_module_spec;
4315 symfile_uuid_module_spec.GetUUID() = symfile_module_spec.GetUUID();
4316 target->GetImages().FindModules(symfile_uuid_module_spec,
4317 matching_modules);
4318 }
4319 }
4320
4321 if (matching_modules.IsEmpty()) {
4322 // No matches yet. Iterate through the module specs to find a UUID
4323 // value that we can match up to an image in our target.
4324 const size_t num_symfile_module_specs = symfile_module_specs.GetSize();
4325 for (size_t i = 0;
4326 i < num_symfile_module_specs && matching_modules.IsEmpty(); ++i) {
4327 if (symfile_module_specs.GetModuleSpecAtIndex(
4328 i, symfile_module_spec)) {
4329 if (symfile_module_spec.GetUUID().IsValid()) {
4330 // It has a UUID. Look for this UUID in the target modules.
4331 ModuleSpec symfile_uuid_module_spec;
4332 symfile_uuid_module_spec.GetUUID() =
4333 symfile_module_spec.GetUUID();
4334 target->GetImages().FindModules(symfile_uuid_module_spec,
4335 matching_modules);
4336 }
4337 }
4338 }
4339 }
4340 }
4341
4342 // Just try to match up the file by basename if we have no matches at
4343 // this point. For example, module foo might have symbols in foo.debug.
4344 if (matching_modules.IsEmpty())
4345 target->GetImages().FindModules(module_spec, matching_modules);
4346
4347 while (matching_modules.IsEmpty()) {
4348 ConstString filename_no_extension(
4350 // Empty string returned, let's bail
4351 if (!filename_no_extension)
4352 break;
4353
4354 // Check if there was no extension to strip and the basename is the same
4355 if (filename_no_extension == module_spec.GetFileSpec().GetFilename())
4356 break;
4357
4358 // Replace basename with one fewer extension
4359 module_spec.GetFileSpec().SetFilename(filename_no_extension);
4360 target->GetImages().FindModules(module_spec, matching_modules);
4361 }
4362
4363 if (matching_modules.GetSize() > 1) {
4364 result.AppendErrorWithFormat("multiple modules match symbol file '%s', "
4365 "use the --uuid option to resolve the "
4366 "ambiguity.\n",
4367 symfile_path);
4368 return false;
4369 }
4370
4371 if (matching_modules.GetSize() == 1) {
4372 ModuleSP module_sp(matching_modules.GetModuleAtIndex(0));
4373
4374 // The module has not yet created its symbol vendor, we can just give
4375 // the existing target module the symfile path to use for when it
4376 // decides to create it!
4377 module_sp->SetSymbolFileFileSpec(symbol_fspec);
4378
4379 SymbolFile *symbol_file =
4380 module_sp->GetSymbolFile(true, &result.GetErrorStream());
4381 if (symbol_file) {
4382 ObjectFile *object_file = symbol_file->GetObjectFile();
4383 if (object_file && object_file->GetFileSpec() == symbol_fspec) {
4384 // Provide feedback that the symfile has been successfully added.
4385 const FileSpec &module_fs = module_sp->GetFileSpec();
4387 "symbol file '%s' has been added to '%s'\n", symfile_path,
4388 module_fs.GetPath().c_str());
4389
4390 // Let clients know something changed in the module if it is
4391 // currently loaded
4392 ModuleList module_list;
4393 module_list.Append(module_sp);
4394 target->SymbolsDidLoad(module_list);
4395
4396 // Make sure we load any scripting resources that may be embedded
4397 // in the debug info files in case the platform supports that.
4398 Status error;
4399 StreamString feedback_stream;
4400 module_sp->LoadScriptingResourceInTarget(target, error,
4401 feedback_stream);
4402 if (error.Fail() && error.AsCString())
4404 "unable to load scripting data for module %s - error "
4405 "reported was %s",
4406 module_sp->GetFileSpec()
4407 .GetFileNameStrippingExtension()
4408 .GetCString(),
4409 error.AsCString());
4410 else if (feedback_stream.GetSize())
4411 result.AppendWarning(feedback_stream.GetData());
4412
4413 flush = true;
4415 return true;
4416 }
4417 }
4418 // Clear the symbol file spec if anything went wrong
4419 module_sp->SetSymbolFileFileSpec(FileSpec());
4420 }
4421
4422 StreamString ss_symfile_uuid;
4423 if (module_spec.GetUUID().IsValid()) {
4424 ss_symfile_uuid << " (";
4425 module_spec.GetUUID().Dump(ss_symfile_uuid);
4426 ss_symfile_uuid << ')';
4427 }
4428 result.AppendErrorWithFormat(
4429 "symbol file '%s'%s does not match any existing module%s\n",
4430 symfile_path, ss_symfile_uuid.GetData(),
4431 !llvm::sys::fs::is_regular_file(symbol_fspec.GetPath())
4432 ? "\n please specify the full path to the symbol file"
4433 : "");
4434 return false;
4435 }
4436
4438 CommandReturnObject &result, bool &flush) {
4439 Status error;
4441 if (module_spec.GetSymbolFileSpec())
4442 return AddModuleSymbols(m_exe_ctx.GetTargetPtr(), module_spec, flush,
4443 result);
4444 } else {
4445 result.SetError(std::move(error));
4446 }
4447 return false;
4448 }
4449
4450 bool AddSymbolsForUUID(CommandReturnObject &result, bool &flush) {
4451 assert(m_uuid_option_group.GetOptionValue().OptionWasSet());
4452
4453 ModuleSpec module_spec;
4454 module_spec.GetUUID() =
4455 m_uuid_option_group.GetOptionValue().GetCurrentValue();
4456
4457 if (!DownloadObjectAndSymbolFile(module_spec, result, flush)) {
4458 StreamString error_strm;
4459 error_strm.PutCString("unable to find debug symbols for UUID ");
4460 module_spec.GetUUID().Dump(error_strm);
4461 result.AppendError(error_strm.GetString());
4462 return false;
4463 }
4464
4465 return true;
4466 }
4467
4468 bool AddSymbolsForFile(CommandReturnObject &result, bool &flush) {
4469 assert(m_file_option.GetOptionValue().OptionWasSet());
4470
4471 ModuleSpec module_spec;
4472 module_spec.GetFileSpec() =
4473 m_file_option.GetOptionValue().GetCurrentValue();
4474
4475 Target *target = m_exe_ctx.GetTargetPtr();
4476 ModuleSP module_sp(target->GetImages().FindFirstModule(module_spec));
4477 if (module_sp) {
4478 module_spec.GetFileSpec() = module_sp->GetFileSpec();
4479 module_spec.GetPlatformFileSpec() = module_sp->GetPlatformFileSpec();
4480 module_spec.GetUUID() = module_sp->GetUUID();
4481 module_spec.GetArchitecture() = module_sp->GetArchitecture();
4482 } else {
4483 module_spec.GetArchitecture() = target->GetArchitecture();
4484 }
4485
4486 if (!DownloadObjectAndSymbolFile(module_spec, result, flush)) {
4487 StreamString error_strm;
4488 error_strm.PutCString(
4489 "unable to find debug symbols for the executable file ");
4490 error_strm << module_spec.GetFileSpec();
4491 result.AppendError(error_strm.GetString());
4492 return false;
4493 }
4494
4495 return true;
4496 }
4497
4498 bool AddSymbolsForFrame(CommandReturnObject &result, bool &flush) {
4499 assert(m_current_frame_option.GetOptionValue().OptionWasSet());
4500
4501 Process *process = m_exe_ctx.GetProcessPtr();
4502 if (!process) {
4503 result.AppendError(
4504 "a process must exist in order to use the --frame option");
4505 return false;
4506 }
4507
4508 const StateType process_state = process->GetState();
4509 if (!StateIsStoppedState(process_state, true)) {
4510 result.AppendErrorWithFormat("process is not stopped: %s",
4511 StateAsCString(process_state));
4512 return false;
4513 }
4514
4515 StackFrame *frame = m_exe_ctx.GetFramePtr();
4516 if (!frame) {
4517 result.AppendError("invalid current frame");
4518 return false;
4519 }
4520
4521 ModuleSP frame_module_sp(
4522 frame->GetSymbolContext(eSymbolContextModule).module_sp);
4523 if (!frame_module_sp) {
4524 result.AppendError("frame has no module");
4525 return false;
4526 }
4527
4528 ModuleSpec module_spec;
4529 module_spec.GetUUID() = frame_module_sp->GetUUID();
4530 module_spec.GetArchitecture() = frame_module_sp->GetArchitecture();
4531 module_spec.GetFileSpec() = frame_module_sp->GetPlatformFileSpec();
4532
4533 if (!DownloadObjectAndSymbolFile(module_spec, result, flush)) {
4534 result.AppendError("unable to find debug symbols for the current frame");
4535 return false;
4536 }
4537
4538 return true;
4539 }
4540
4541 bool AddSymbolsForStack(CommandReturnObject &result, bool &flush) {
4542 assert(m_current_stack_option.GetOptionValue().OptionWasSet());
4543
4544 Process *process = m_exe_ctx.GetProcessPtr();
4545 if (!process) {
4546 result.AppendError(
4547 "a process must exist in order to use the --stack option");
4548 return false;
4549 }
4550
4551 const StateType process_state = process->GetState();
4552 if (!StateIsStoppedState(process_state, true)) {
4553 result.AppendErrorWithFormat("process is not stopped: %s",
4554 StateAsCString(process_state));
4555 return false;
4556 }
4557
4558 Thread *thread = m_exe_ctx.GetThreadPtr();
4559 if (!thread) {
4560 result.AppendError("invalid current thread");
4561 return false;
4562 }
4563
4564 bool symbols_found = false;
4565 uint32_t frame_count = thread->GetStackFrameCount();
4566 for (uint32_t i = 0; i < frame_count; ++i) {
4567 lldb::StackFrameSP frame_sp = thread->GetStackFrameAtIndex(i);
4568
4569 ModuleSP frame_module_sp(
4570 frame_sp->GetSymbolContext(eSymbolContextModule).module_sp);
4571 if (!frame_module_sp)
4572 continue;
4573
4574 ModuleSpec module_spec;
4575 module_spec.GetUUID() = frame_module_sp->GetUUID();
4576 module_spec.GetFileSpec() = frame_module_sp->GetPlatformFileSpec();
4577 module_spec.GetArchitecture() = frame_module_sp->GetArchitecture();
4578
4579 bool current_frame_flush = false;
4580 if (DownloadObjectAndSymbolFile(module_spec, result, current_frame_flush))
4581 symbols_found = true;
4582 flush |= current_frame_flush;
4583 }
4584
4585 if (!symbols_found) {
4586 result.AppendError(
4587 "unable to find debug symbols in the current call stack");
4588 return false;
4589 }
4590
4591 return true;
4592 }
4593
4594 void DoExecute(Args &args, CommandReturnObject &result) override {
4595 Target *target = m_exe_ctx.GetTargetPtr();
4597 bool flush = false;
4598 ModuleSpec module_spec;
4599 const bool uuid_option_set =
4600 m_uuid_option_group.GetOptionValue().OptionWasSet();
4601 const bool file_option_set = m_file_option.GetOptionValue().OptionWasSet();
4602 const bool frame_option_set =
4603 m_current_frame_option.GetOptionValue().OptionWasSet();
4604 const bool stack_option_set =
4605 m_current_stack_option.GetOptionValue().OptionWasSet();
4606 const size_t argc = args.GetArgumentCount();
4607
4608 if (argc == 0) {
4609 if (uuid_option_set)
4610 AddSymbolsForUUID(result, flush);
4611 else if (file_option_set)
4612 AddSymbolsForFile(result, flush);
4613 else if (frame_option_set)
4614 AddSymbolsForFrame(result, flush);
4615 else if (stack_option_set)
4616 AddSymbolsForStack(result, flush);
4617 else
4618 result.AppendError("one or more symbol file paths must be specified, "
4619 "or options must be specified");
4620 } else {
4621 if (uuid_option_set) {
4622 result.AppendError("specify either one or more paths to symbol files "
4623 "or use the --uuid option without arguments");
4624 } else if (frame_option_set) {
4625 result.AppendError("specify either one or more paths to symbol files "
4626 "or use the --frame option without arguments");
4627 } else if (file_option_set && argc > 1) {
4628 result.AppendError("specify at most one symbol file path when "
4629 "--shlib option is set");
4630 } else {
4631 PlatformSP platform_sp(target->GetPlatform());
4632
4633 for (auto &entry : args.entries()) {
4634 if (!entry.ref().empty()) {
4635 auto &symbol_file_spec = module_spec.GetSymbolFileSpec();
4636 symbol_file_spec.SetFile(entry.ref(), FileSpec::Style::native);
4637 FileSystem::Instance().Resolve(symbol_file_spec);
4638 if (file_option_set) {
4639 module_spec.GetFileSpec() =
4640 m_file_option.GetOptionValue().GetCurrentValue();
4641 }
4642 if (platform_sp) {
4643 FileSpec symfile_spec;
4644 if (platform_sp
4645 ->ResolveSymbolFile(*target, module_spec, symfile_spec)
4646 .Success())
4647 module_spec.GetSymbolFileSpec() = symfile_spec;
4648 }
4649
4650 bool symfile_exists =
4652
4653 if (symfile_exists) {
4654 if (!AddModuleSymbols(target, module_spec, flush, result))
4655 break;
4656 } else {
4657 std::string resolved_symfile_path =
4658 module_spec.GetSymbolFileSpec().GetPath();
4659 if (resolved_symfile_path != entry.ref()) {
4660 result.AppendErrorWithFormat(
4661 "invalid module path '%s' with resolved path '%s'\n",
4662 entry.c_str(), resolved_symfile_path.c_str());
4663 break;
4664 }
4665 result.AppendErrorWithFormat("invalid module path '%s'\n",
4666 entry.c_str());
4667 break;
4668 }
4669 }
4670 }
4671 }
4672 }
4673
4674 if (flush) {
4675 Process *process = m_exe_ctx.GetProcessPtr();
4676 if (process)
4677 process->Flush();
4678 }
4679 }
4680
4686};
4687
4688#pragma mark CommandObjectTargetSymbols
4689
4690// CommandObjectTargetSymbols
4691
4693public:
4694 // Constructors and Destructors
4697 interpreter, "target symbols",
4698 "Commands for adding and managing debug symbol files.",
4699 "target symbols <sub-command> ...") {
4701 "add", CommandObjectSP(new CommandObjectTargetSymbolsAdd(interpreter)));
4702 }
4703
4704 ~CommandObjectTargetSymbols() override = default;
4705
4706private:
4707 // For CommandObjectTargetModules only
4711};
4712
4713#pragma mark CommandObjectTargetStopHookAdd
4714
4715// CommandObjectTargetStopHookAdd
4716#define LLDB_OPTIONS_target_stop_hook_add
4717#include "CommandOptions.inc"
4718
4721public:
4723 public:
4725
4726 ~CommandOptions() override = default;
4727
4728 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
4729 return llvm::ArrayRef(g_target_stop_hook_add_options);
4730 }
4731
4732 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
4733 ExecutionContext *execution_context) override {
4734 Status error;
4735 const int short_option =
4736 g_target_stop_hook_add_options[option_idx].short_option;
4737
4738 switch (short_option) {
4739 case 'c':
4740 m_class_name = std::string(option_arg);
4741 m_sym_ctx_specified = true;
4742 break;
4743
4744 case 'e':
4745 if (option_arg.getAsInteger(0, m_line_end)) {
4747 "invalid end line number: \"%s\"", option_arg.str().c_str());
4748 break;
4749 }
4750 m_sym_ctx_specified = true;
4751 break;
4752
4753 case 'G': {
4754 bool value, success;
4755 value = OptionArgParser::ToBoolean(option_arg, false, &success);
4756 if (success) {
4757 m_auto_continue = value;
4758 } else
4760 "invalid boolean value '%s' passed for -G option",
4761 option_arg.str().c_str());
4762 } break;
4763 case 'l':
4764 if (option_arg.getAsInteger(0, m_line_start)) {
4766 "invalid start line number: \"%s\"", option_arg.str().c_str());
4767 break;
4768 }
4769 m_sym_ctx_specified = true;
4770 break;
4771
4772 case 'i':
4773 m_no_inlines = true;
4774 break;
4775
4776 case 'n':
4777 m_function_name = std::string(option_arg);
4778 m_func_name_type_mask |= eFunctionNameTypeAuto;
4779 m_sym_ctx_specified = true;
4780 break;
4781
4782 case 'f':
4783 m_file_name = std::string(option_arg);
4784 m_sym_ctx_specified = true;
4785 break;
4786
4787 case 's':
4788 m_module_name = std::string(option_arg);
4789 m_sym_ctx_specified = true;
4790 break;
4791
4792 case 't':
4793 if (option_arg.getAsInteger(0, m_thread_id))
4795 "invalid thread id string '%s'", option_arg.str().c_str());
4796 m_thread_specified = true;
4797 break;
4798
4799 case 'T':
4800 m_thread_name = std::string(option_arg);
4801 m_thread_specified = true;
4802 break;
4803
4804 case 'q':
4805 m_queue_name = std::string(option_arg);
4806 m_thread_specified = true;
4807 break;
4808
4809 case 'x':
4810 if (option_arg.getAsInteger(0, m_thread_index))
4812 "invalid thread index string '%s'", option_arg.str().c_str());
4813 m_thread_specified = true;
4814 break;
4815
4816 case 'o':
4817 m_use_one_liner = true;
4818 m_one_liner.push_back(std::string(option_arg));
4819 break;
4820
4821 case 'I': {
4822 bool value, success;
4823 value = OptionArgParser::ToBoolean(option_arg, false, &success);
4824 if (success)
4825 m_at_initial_stop = value;
4826 else
4828 "invalid boolean value '%s' passed for -F option",
4829 option_arg.str().c_str());
4830 } break;
4831
4832 default:
4833 llvm_unreachable("Unimplemented option");
4834 }
4835 return error;
4836 }
4837
4838 void OptionParsingStarting(ExecutionContext *execution_context) override {
4839 m_class_name.clear();
4840 m_function_name.clear();
4841 m_line_start = 0;
4843 m_file_name.clear();
4844 m_module_name.clear();
4845 m_func_name_type_mask = eFunctionNameTypeAuto;
4848 m_thread_name.clear();
4849 m_queue_name.clear();
4850
4851 m_no_inlines = false;
4852 m_sym_ctx_specified = false;
4853 m_thread_specified = false;
4854
4855 m_use_one_liner = false;
4856 m_one_liner.clear();
4857 m_auto_continue = false;
4858 m_at_initial_stop = true;
4859 }
4860
4861 std::string m_class_name;
4862 std::string m_function_name;
4863 uint32_t m_line_start = 0;
4865 std::string m_file_name;
4866 std::string m_module_name;
4868 eFunctionNameTypeAuto; // A pick from lldb::FunctionNameType.
4871 std::string m_thread_name;
4872 std::string m_queue_name;
4874 bool m_no_inlines = false;
4876 // Instance variables to hold the values for one_liner options.
4877 bool m_use_one_liner = false;
4878 std::vector<std::string> m_one_liner;
4880
4881 bool m_auto_continue = false;
4882 };
4883
4885 : CommandObjectParsed(interpreter, "target stop-hook add",
4886 "Add a hook to be executed when the target stops."
4887 "The hook can either be a list of commands or an "
4888 "appropriately defined Python class. You can also "
4889 "add filters so the hook only runs a certain stop "
4890 "points.",
4891 "target stop-hook add"),
4894 m_python_class_options("scripted stop-hook", true, 'P') {
4896 R"(
4897Command Based stop-hooks:
4898-------------------------
4899 Stop hooks can run a list of lldb commands by providing one or more
4900 --one-liner options. The commands will get run in the order they are added.
4901 Or you can provide no commands, in which case you will enter a command editor
4902 where you can enter the commands to be run.
4903
4904Python Based Stop Hooks:
4905------------------------
4906 Stop hooks can be implemented with a suitably defined Python class, whose name
4907 is passed in the --python-class option.
4908
4909 When the stop hook is added, the class is initialized by calling:
4910
4911 def __init__(self, target, extra_args, internal_dict):
4912
4913 target: The target that the stop hook is being added to.
4914 extra_args: An SBStructuredData Dictionary filled with the -key -value
4915 option pairs passed to the command.
4916 dict: An implementation detail provided by lldb.
4917
4918 Then when the stop-hook triggers, lldb will run the 'handle_stop' method.
4919 The method has the signature:
4921 def handle_stop(self, exe_ctx, stream):
4922
4923 exe_ctx: An SBExecutionContext for the thread that has stopped.
4924 stream: An SBStream, anything written to this stream will be printed in the
4925 the stop message when the process stops.
4926
4927 Return Value: The method returns "should_stop". If should_stop is false
4928 from all the stop hook executions on threads that stopped
4929 with a reason, then the process will continue. Note that this
4930 will happen only after all the stop hooks are run.
4931
4932Filter Options:
4933---------------
4934 Stop hooks can be set to always run, or to only run when the stopped thread
4935 matches the filter options passed on the command line. The available filter
4936 options include a shared library or a thread or queue specification,
4937 a line range in a source file, a function name or a class name.
4938 )");
4941 LLDB_OPT_SET_FROM_TO(4, 6));
4942 m_all_options.Append(&m_options);
4943 m_all_options.Finalize();
4944 }
4945
4946 ~CommandObjectTargetStopHookAdd() override = default;
4947
4948 Options *GetOptions() override { return &m_all_options; }
4949
4950protected:
4951 void IOHandlerActivated(IOHandler &io_handler, bool interactive) override {
4952 if (interactive) {
4953 if (lldb::LockableStreamFileSP output_sp =
4954 io_handler.GetOutputStreamFileSP()) {
4955 LockedStreamFile locked_stream = output_sp->Lock();
4956 locked_stream.PutCString(
4957 "Enter your stop hook command(s). Type 'DONE' to end.\n");
4958 }
4959 }
4960 }
4961
4962 void IOHandlerInputComplete(IOHandler &io_handler,
4963 std::string &line) override {
4964 if (m_stop_hook_sp) {
4965 if (line.empty()) {
4966 if (lldb::LockableStreamFileSP error_sp =
4967 io_handler.GetErrorStreamFileSP()) {
4968 LockedStreamFile locked_stream = error_sp->Lock();
4969 locked_stream.Printf("error: stop hook #%" PRIu64
4970 " aborted, no commands.\n",
4971 m_stop_hook_sp->GetID());
4972 }
4974 } else {
4975 // The IOHandler editor is only for command lines stop hooks:
4976 Target::StopHookCommandLine *hook_ptr =
4977 static_cast<Target::StopHookCommandLine *>(m_stop_hook_sp.get());
4978
4979 hook_ptr->SetActionFromString(line);
4980 if (lldb::LockableStreamFileSP output_sp =
4981 io_handler.GetOutputStreamFileSP()) {
4982 LockedStreamFile locked_stream = output_sp->Lock();
4983 locked_stream.Printf("Stop hook #%" PRIu64 " added.\n",
4984 m_stop_hook_sp->GetID());
4985 }
4986 }
4987 m_stop_hook_sp.reset();
4988 }
4989 io_handler.SetIsDone(true);
4990 }
4991
4992 void DoExecute(Args &command, CommandReturnObject &result) override {
4993 m_stop_hook_sp.reset();
4994
4995 Target &target = GetTarget();
4996 Target::StopHookSP new_hook_sp =
4997 target.CreateStopHook(m_python_class_options.GetName().empty() ?
4998 Target::StopHook::StopHookKind::CommandBased
4999 : Target::StopHook::StopHookKind::ScriptBased);
5000
5001 // First step, make the specifier.
5002 std::unique_ptr<SymbolContextSpecifier> specifier_up;
5003 if (m_options.m_sym_ctx_specified) {
5004 specifier_up = std::make_unique<SymbolContextSpecifier>(
5005 GetDebugger().GetSelectedTarget());
5006
5007 if (!m_options.m_module_name.empty()) {
5008 specifier_up->AddSpecification(
5009 m_options.m_module_name.c_str(),
5011 }
5012
5013 if (!m_options.m_class_name.empty()) {
5014 specifier_up->AddSpecification(
5015 m_options.m_class_name.c_str(),
5017 }
5018
5019 if (!m_options.m_file_name.empty()) {
5020 specifier_up->AddSpecification(m_options.m_file_name.c_str(),
5022 }
5023
5024 if (m_options.m_line_start != 0) {
5025 specifier_up->AddLineSpecification(
5026 m_options.m_line_start,
5028 }
5029
5030 if (m_options.m_line_end != UINT_MAX) {
5031 specifier_up->AddLineSpecification(
5033 }
5034
5035 if (!m_options.m_function_name.empty()) {
5036 specifier_up->AddSpecification(
5037 m_options.m_function_name.c_str(),
5039 }
5040 }
5041
5042 if (specifier_up)
5043 new_hook_sp->SetSpecifier(specifier_up.release());
5044
5045 // Should we run at the initial stop:
5046 new_hook_sp->SetRunAtInitialStop(m_options.m_at_initial_stop);
5047
5048 // Next see if any of the thread options have been entered:
5049
5050 if (m_options.m_thread_specified) {
5051 ThreadSpec *thread_spec = new ThreadSpec();
5052
5053 if (m_options.m_thread_id != LLDB_INVALID_THREAD_ID) {
5054 thread_spec->SetTID(m_options.m_thread_id);
5055 }
5056
5057 if (m_options.m_thread_index != UINT32_MAX)
5058 thread_spec->SetIndex(m_options.m_thread_index);
5059
5060 if (!m_options.m_thread_name.empty())
5061 thread_spec->SetName(m_options.m_thread_name.c_str());
5063 if (!m_options.m_queue_name.empty())
5064 thread_spec->SetQueueName(m_options.m_queue_name.c_str());
5066 new_hook_sp->SetThreadSpecifier(thread_spec);
5067 }
5068
5069 new_hook_sp->SetAutoContinue(m_options.m_auto_continue);
5071 // This is a command line stop hook:
5072 Target::StopHookCommandLine *hook_ptr =
5073 static_cast<Target::StopHookCommandLine *>(new_hook_sp.get());
5075 result.AppendMessageWithFormat("Stop hook #%" PRIu64 " added.\n",
5076 new_hook_sp->GetID());
5077 } else if (!m_python_class_options.GetName().empty()) {
5078 // This is a scripted stop hook:
5079 Target::StopHookScripted *hook_ptr =
5080 static_cast<Target::StopHookScripted *>(new_hook_sp.get());
5081 Status error = hook_ptr->SetScriptCallback(
5082 m_python_class_options.GetName(),
5083 m_python_class_options.GetStructuredData());
5084 if (error.Success())
5085 result.AppendMessageWithFormat("Stop hook #%" PRIu64 " added.\n",
5086 new_hook_sp->GetID());
5087 else {
5088 // FIXME: Set the stop hook ID counter back.
5089 result.AppendErrorWithFormat("Couldn't add stop hook: %s",
5090 error.AsCString());
5091 target.UndoCreateStopHook(new_hook_sp->GetID());
5092 return;
5093 }
5094 } else {
5095 m_stop_hook_sp = new_hook_sp;
5096 m_interpreter.GetLLDBCommandsFromIOHandler("> ", // Prompt
5097 *this); // IOHandlerDelegate
5098 }
5100 }
5101
5102private:
5104 OptionGroupPythonClassWithDict m_python_class_options;
5105 OptionGroupOptions m_all_options;
5106
5108};
5109
5110#pragma mark CommandObjectTargetStopHookDelete
5111
5112// CommandObjectTargetStopHookDelete
5113
5115public:
5117 : CommandObjectParsed(interpreter, "target stop-hook delete",
5118 "Delete a stop-hook.",
5119 "target stop-hook delete [<idx>]") {
5121 }
5122
5124
5125 void
5127 OptionElementVector &opt_element_vector) override {
5128 if (request.GetCursorIndex())
5129 return;
5130 CommandObject::HandleArgumentCompletion(request, opt_element_vector);
5131 }
5132
5133protected:
5134 void DoExecute(Args &command, CommandReturnObject &result) override {
5135 Target &target = GetTarget();
5136 // FIXME: see if we can use the breakpoint id style parser?
5137 size_t num_args = command.GetArgumentCount();
5138 if (num_args == 0) {
5139 if (!m_interpreter.Confirm("Delete all stop hooks?", true)) {
5141 return;
5142 } else {
5143 target.RemoveAllStopHooks();
5144 }
5145 } else {
5146 for (size_t i = 0; i < num_args; i++) {
5147 lldb::user_id_t user_id;
5148 if (!llvm::to_integer(command.GetArgumentAtIndex(i), user_id)) {
5149 result.AppendErrorWithFormat("invalid stop hook id: \"%s\".\n",
5150 command.GetArgumentAtIndex(i));
5151 return;
5152 }
5153 if (!target.RemoveStopHookByID(user_id)) {
5154 result.AppendErrorWithFormat("unknown stop hook id: \"%s\".\n",
5155 command.GetArgumentAtIndex(i));
5156 return;
5157 }
5158 }
5159 }
5161 }
5162};
5163
5164#pragma mark CommandObjectTargetStopHookEnableDisable
5165
5166// CommandObjectTargetStopHookEnableDisable
5167
5169public:
5171 bool enable, const char *name,
5172 const char *help, const char *syntax)
5173 : CommandObjectParsed(interpreter, name, help, syntax), m_enable(enable) {
5175 }
5176
5178
5179 void
5181 OptionElementVector &opt_element_vector) override {
5182 if (request.GetCursorIndex())
5183 return;
5184 CommandObject::HandleArgumentCompletion(request, opt_element_vector);
5185 }
5186
5187protected:
5188 void DoExecute(Args &command, CommandReturnObject &result) override {
5189 Target &target = GetTarget();
5190 // FIXME: see if we can use the breakpoint id style parser?
5191 size_t num_args = command.GetArgumentCount();
5192 bool success;
5193
5194 if (num_args == 0) {
5196 } else {
5197 for (size_t i = 0; i < num_args; i++) {
5198 lldb::user_id_t user_id;
5199 if (!llvm::to_integer(command.GetArgumentAtIndex(i), user_id)) {
5200 result.AppendErrorWithFormat("invalid stop hook id: \"%s\".\n",
5201 command.GetArgumentAtIndex(i));
5202 return;
5203 }
5204 success = target.SetStopHookActiveStateByID(user_id, m_enable);
5205 if (!success) {
5206 result.AppendErrorWithFormat("unknown stop hook id: \"%s\".\n",
5207 command.GetArgumentAtIndex(i));
5208 return;
5209 }
5210 }
5211 }
5213 }
5214
5215private:
5217};
5218
5219#pragma mark CommandObjectTargetStopHookList
5220
5221// CommandObjectTargetStopHookList
5222
5224public:
5226 : CommandObjectParsed(interpreter, "target stop-hook list",
5227 "List all stop-hooks.", "target stop-hook list") {}
5228
5230
5231protected:
5232 void DoExecute(Args &command, CommandReturnObject &result) override {
5233 Target &target = GetTarget();
5234
5235 size_t num_hooks = target.GetNumStopHooks();
5236 if (num_hooks == 0) {
5237 result.GetOutputStream().PutCString("No stop hooks.\n");
5238 } else {
5239 for (size_t i = 0; i < num_hooks; i++) {
5240 Target::StopHookSP this_hook = target.GetStopHookAtIndex(i);
5241 if (i > 0)
5242 result.GetOutputStream().PutCString("\n");
5243 this_hook->GetDescription(result.GetOutputStream(),
5245 }
5246 }
5248 }
5249};
5250
5251#pragma mark CommandObjectMultiwordTargetStopHooks
5252
5253// CommandObjectMultiwordTargetStopHooks
5254
5256public:
5259 interpreter, "target stop-hook",
5260 "Commands for operating on debugger target stop-hooks.",
5261 "target stop-hook <subcommand> [<subcommand-options>]") {
5263 new CommandObjectTargetStopHookAdd(interpreter)));
5265 "delete",
5267 LoadSubCommand("disable",
5269 interpreter, false, "target stop-hook disable [<id>]",
5270 "Disable a stop-hook.", "target stop-hook disable")));
5271 LoadSubCommand("enable",
5273 interpreter, true, "target stop-hook enable [<id>]",
5274 "Enable a stop-hook.", "target stop-hook enable")));
5276 interpreter)));
5277 }
5278
5280};
5281
5282#pragma mark CommandObjectTargetDumpTypesystem
5283
5284/// Dumps the TypeSystem of the selected Target.
5286public:
5289 interpreter, "target dump typesystem",
5290 "Dump the state of the target's internal type system. Intended to "
5291 "be used for debugging LLDB itself.",
5292 nullptr, eCommandRequiresTarget) {}
5293
5295
5296protected:
5297 void DoExecute(Args &command, CommandReturnObject &result) override {
5298 // Go over every scratch TypeSystem and dump to the command output.
5299 for (lldb::TypeSystemSP ts : GetTarget().GetScratchTypeSystems())
5300 if (ts)
5301 ts->Dump(result.GetOutputStream().AsRawOstream(), "",
5302 GetCommandInterpreter().GetDebugger().GetUseColor());
5303
5305 }
5306};
5307
5308#pragma mark CommandObjectTargetDumpSectionLoadList
5309
5310/// Dumps the SectionLoadList of the selected Target.
5312public:
5315 interpreter, "target dump section-load-list",
5316 "Dump the state of the target's internal section load list. "
5317 "Intended to be used for debugging LLDB itself.",
5318 nullptr, eCommandRequiresTarget) {}
5319
5321
5322protected:
5323 void DoExecute(Args &command, CommandReturnObject &result) override {
5324 Target &target = GetTarget();
5325 target.DumpSectionLoadList(result.GetOutputStream());
5327 }
5328};
5329
5330#pragma mark CommandObjectTargetDump
5331
5332/// Multi-word command for 'target dump'.
5334public:
5335 // Constructors and Destructors
5338 interpreter, "target dump",
5339 "Commands for dumping information about the target.",
5340 "target dump [typesystem|section-load-list]") {
5342 "typesystem",
5344 LoadSubCommand("section-load-list",
5346 interpreter)));
5347 }
5348
5349 ~CommandObjectTargetDump() override = default;
5350};
5351
5352#pragma mark CommandObjectMultiwordTarget
5353
5354// CommandObjectMultiwordTarget
5355
5357 CommandInterpreter &interpreter)
5358 : CommandObjectMultiword(interpreter, "target",
5359 "Commands for operating on debugger targets.",
5360 "target <subcommand> [<subcommand-options>]") {
5361 LoadSubCommand("create",
5362 CommandObjectSP(new CommandObjectTargetCreate(interpreter)));
5363 LoadSubCommand("delete",
5364 CommandObjectSP(new CommandObjectTargetDelete(interpreter)));
5365 LoadSubCommand("dump",
5366 CommandObjectSP(new CommandObjectTargetDump(interpreter)));
5367 LoadSubCommand("list",
5368 CommandObjectSP(new CommandObjectTargetList(interpreter)));
5369 LoadSubCommand("select",
5370 CommandObjectSP(new CommandObjectTargetSelect(interpreter)));
5371 LoadSubCommand("show-launch-environment",
5373 interpreter)));
5375 "stop-hook",
5377 LoadSubCommand("modules",
5379 LoadSubCommand("symbols",
5381 LoadSubCommand("variable",
5383}
5384
static bool GetSeparateDebugInfoList(StructuredData::Array &list, Module *module, bool errors_only, bool load_all_debug_info)
static uint32_t DumpTargetList(TargetList &target_list, bool show_stopped_process_status, Stream &strm)
static void DumpModuleUUID(Stream &strm, Module *module)
static void DumpModuleSections(CommandInterpreter &interpreter, Stream &strm, Module *module)
static void DumpModuleArchitecture(Stream &strm, Module *module, bool full_triple, uint32_t width)
static bool LookupAddressInModule(CommandInterpreter &interpreter, Stream &strm, Module *module, uint32_t resolve_mask, lldb::addr_t raw_addr, lldb::addr_t offset, bool verbose, bool all_ranges)
static void DumpTargetInfo(uint32_t target_idx, Target *target, const char *prefix_cstr, bool show_stopped_process_status, Stream &strm)
static void DumpDirectory(Stream &strm, const FileSpec *file_spec_ptr, uint32_t width)
static uint32_t LookupSymbolInModule(CommandInterpreter &interpreter, Stream &strm, Module *module, const char *name, bool name_is_regex, bool verbose, bool all_ranges)
static size_t LookupTypeInModule(Target *target, CommandInterpreter &interpreter, Stream &strm, Module *module, const char *name_cstr, bool name_is_regex)
static bool DumpModuleSymbolFile(Stream &strm, Module *module)
static void DumpFullpath(Stream &strm, const FileSpec *file_spec_ptr, uint32_t width)
static void DumpDwoFilesTable(Stream &strm, StructuredData::Array &dwo_listings)
static size_t LookupFunctionInModule(CommandInterpreter &interpreter, Stream &strm, Module *module, const char *name, bool name_is_regex, const ModuleFunctionSearchOptions &options, bool verbose, bool all_ranges)
static size_t LookupTypeHere(Target *target, CommandInterpreter &interpreter, Stream &strm, Module &module, const char *name_cstr, bool name_is_regex)
static uint32_t DumpCompileUnitLineTable(CommandInterpreter &interpreter, Stream &strm, Module *module, const FileSpec &file_spec, lldb::DescriptionLevel desc_level)
static void DumpBasename(Stream &strm, const FileSpec *file_spec_ptr, uint32_t width)
static size_t DumpModuleObjfileHeaders(Stream &strm, ModuleList &module_list)
static uint32_t LookupFileAndLineInModule(CommandInterpreter &interpreter, Stream &strm, Module *module, const FileSpec &file_spec, uint32_t line, bool check_inlines, bool verbose, bool all_ranges)
static void DumpSymbolContextList(ExecutionContextScope *exe_scope, Stream &strm, const SymbolContextList &sc_list, bool verbose, bool all_ranges, std::optional< Stream::HighlightSettings > settings=std::nullopt)
static void DumpOsoFilesTable(Stream &strm, StructuredData::Array &oso_listings)
static size_t FindModulesByName(Target *target, const char *module_name, ModuleList &module_list, bool check_global_list)
static void DumpModuleSymtab(CommandInterpreter &interpreter, Stream &strm, Module *module, SortOrder sort_order, Mangled::NamePreference name_preference)
static llvm::raw_ostream & error(Stream &strm)
#define INTERRUPT_REQUESTED(debugger,...)
This handy define will keep you from having to generate a report for the interruption by hand.
Definition Debugger.h:458
#define LLDB_LOGF(log,...)
Definition Log.h:376
#define LLDB_SCOPED_TIMERF(...)
Definition Timer.h:86
~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
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
~CommandObjectTargetModulesDumpClangPCMInfo() override=default
CommandObjectTargetModulesDumpClangPCMInfo(CommandInterpreter &interpreter)
void DoExecute(Args &command, CommandReturnObject &result) override
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)
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:150
A section + offset based address class.
Definition Address.h:62
lldb::addr_t GetLoadAddress(Target *target) const
Get the load address.
Definition Address.cpp:301
bool SetLoadAddress(lldb::addr_t load_addr, Target *target, bool allow_section_end=false)
Set the address to represent load_addr.
Definition Address.cpp:1035
@ 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:396
lldb::ModuleSP GetModule() const
Get accessor for the module for this address.
Definition Address.cpp:273
lldb::addr_t GetFileAddress() const
Get the file address.
Definition Address.cpp:281
bool IsValid() const
Check if the object state is valid.
Definition Address.h:355
An architecture specification class.
Definition ArchSpec.h:31
uint32_t GetAddressByteSize() const
Returns the size in bytes of an address of the current architecture.
Definition ArchSpec.cpp:676
bool IsValid() const
Tests if this ArchSpec is valid.
Definition ArchSpec.h:366
void DumpTriple(llvm::raw_ostream &s) const
const char * GetArchitectureName() const
Returns a static string representing the current architecture.
Definition ArchSpec.cpp:539
A command line argument class.
Definition Args.h:33
void Shift()
Shifts the first argument C string value of the array off the argument array.
Definition Args.cpp:295
size_t GetArgumentCount() const
Gets the number of arguments left in this command object.
Definition Args.h:120
llvm::ArrayRef< ArgEntry > entries() const
Definition Args.h:132
const char * GetArgumentAtIndex(size_t idx) const
Gets the NULL terminated C string argument pointer for the argument at index idx.
Definition Args.cpp:273
static bool InvokeCommonCompletionCallbacks(CommandInterpreter &interpreter, uint32_t completion_mask, lldb_private::CompletionRequest &request, SearchFilter *searcher)
ExecutionContext GetExecutionContext() const
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)
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,...
void void AppendError(llvm::StringRef in_string)
const ValueObjectList & GetValueObjectList() const
void AppendWarningWithFormat(const char *format,...) __attribute__((format(printf
void SetStatus(lldb::ReturnStatus status)
void AppendErrorWithFormat(const char *format,...) __attribute__((format(printf
void AppendMessageWithFormat(const char *format,...) __attribute__((format(printf
void void AppendMessageWithFormatv(const char *format, Args &&...args)
void 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
const char * AsCString(const char *value_if_empty=nullptr) const
Get the string value as a C string.
void Dump(Stream *s, const char *value_if_empty=nullptr) const
Dump the object description to a stream.
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:80
TargetList & GetTargetList()
Get accessor for the target list.
Definition Debugger.h:193
bool GetUseColor() const
Definition Debugger.cpp:452
llvm::StringRef GetRegexMatchAnsiSuffix() const
Definition Debugger.cpp:557
llvm::StringRef GetRegexMatchAnsiPrefix() const
Definition Debugger.cpp:551
DumpValueObjectOptions & SetRootValueObjectName(const char *name=nullptr)
DumpValueObjectOptions & SetFormat(lldb::Format format=lldb::eFormatDefault)
"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:57
void SetFile(llvm::StringRef path, Style style)
Change the file specified with a new path.
Definition FileSpec.cpp:174
void SetDirectory(ConstString directory)
Directory string set accessor.
Definition FileSpec.cpp:342
const ConstString & GetFilename() const
Filename string const get accessor.
Definition FileSpec.h:251
const ConstString & GetDirectory() const
Directory string const get accessor.
Definition FileSpec.h:234
ConstString GetFileNameStrippingExtension() const
Return the filename without the extension part.
Definition FileSpec.cpp:414
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
Definition FileSpec.cpp:374
void Dump(llvm::raw_ostream &s) const
Dump this object to a Stream.
Definition FileSpec.cpp:325
llvm::StringRef GetFileNameExtension() const
Extract the extension of the file.
Definition FileSpec.cpp:410
void SetFilename(ConstString filename)
Filename string set accessor.
Definition FileSpec.cpp:352
void Resolve(llvm::SmallVectorImpl< char > &path)
Resolve path to make it canonical.
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()
@ eOpenOptionReadOnly
Definition File.h:51
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:104
void FindFunctions(ConstString name, lldb::FunctionNameType name_type_mask, const ModuleFunctionSearchOptions &options, SymbolContextList &sc_list) const
ModuleIterableNoLocking ModulesNoLocking() const
Definition ModuleList.h:543
static bool ModuleIsInCache(const Module *module_ptr)
void FindGlobalVariables(ConstString name, size_t max_matches, VariableList &variable_list) const
Find global and static variables by name.
std::recursive_mutex & GetMutex() const
Definition ModuleList.h:231
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)
ModuleIterable Modules() const
Definition ModuleList.h:537
size_t GetSize() const
Gets the size of the module list.
bool GetModuleSpecAtIndex(size_t i, ModuleSpec &module_spec) const
Definition ModuleSpec.h:323
bool FindMatchingModuleSpec(const ModuleSpec &module_spec, ModuleSpec &match_module_spec) const
Definition ModuleSpec.h:333
FileSpec & GetPlatformFileSpec()
Definition ModuleSpec.h:65
FileSpec & GetFileSpec()
Definition ModuleSpec.h:53
ArchSpec & GetArchitecture()
Definition ModuleSpec.h:89
FileSpec * GetFileSpecPtr()
Definition ModuleSpec.h:47
FileSpec & GetSymbolFileSpec()
Definition ModuleSpec.h:77
A class that describes an executable image and its associated object and symbol files.
Definition Module.h:90
const lldb_private::UUID & GetUUID()
Get a reference to the UUID value contained in this object.
Definition Module.cpp:350
virtual SymbolFile * GetSymbolFile(bool can_create=true, Stream *feedback_strm=nullptr)
Get the module's symbol file.
Definition Module.cpp:977
static Module * GetAllocatedModuleAtIndex(size_t idx)
Definition Module.cpp:124
static std::recursive_mutex & GetAllocationModuleCollectionMutex()
Definition Module.cpp:106
bool ResolveFileAddress(lldb::addr_t vm_addr, Address &so_addr)
Definition Module.cpp:447
Symtab * GetSymtab(bool can_create=true)
Get the module's symbol table.
Definition Module.cpp:1004
bool MatchesModuleSpec(const ModuleSpec &module_ref)
Definition Module.cpp:1503
static size_t GetNumberAllocatedModules()
Definition Module.cpp:118
const ArchSpec & GetArchitecture() const
Get const accessor for the module architecture.
Definition Module.cpp:1019
std::string GetSpecificationDescription() const
Get the module path and object name.
Definition Module.cpp:1021
const FileSpec & GetFileSpec() const
Get const accessor for the module file specification.
Definition Module.h:454
const llvm::sys::TimePoint & GetModificationTime() const
Definition Module.h:490
A plug-in interface definition class for object file parsers.
Definition ObjectFile.h:45
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:476
virtual FileSpec & GetFileSpec()
Get accessor to the object file specification.
Definition ObjectFile.h:281
virtual lldb_private::Address GetBaseAddress()
Returns base address of this object file.
Definition ObjectFile.h:486
static size_t GetModuleSpecifications(const FileSpec &file, lldb::offset_t file_offset, lldb::offset_t file_size, ModuleSpecList &specs, lldb::DataBufferSP data_sp=lldb::DataBufferSP())
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
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 RemapPath(ConstString path, ConstString &new_path) const
bool GetPathsAtIndex(uint32_t idx, ConstString &path, ConstString &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:357
ThreadList & GetThreadList()
Definition Process.h:2253
void Flush()
Flush all data in the process.
Definition Process.cpp:5890
lldb::StateType GetState()
Get accessor for the current process state.
Definition Process.cpp:1285
const lldb::ABISP & GetABI()
Definition Process.cpp:1481
bool IsValid() const
Test if this object contains a valid regular expression.
lldb::SectionSP FindSectionByName(ConstString section_dstr) const
Definition Section.cpp:558
void Dump(llvm::raw_ostream &s, unsigned indent, Target *target, bool show_header, uint32_t depth) const
Definition Section.cpp:644
This base class provides an interface to stack frames.
Definition StackFrame.h:44
const SymbolContext & GetSymbolContext(lldb::SymbolContextItem resolve_scope)
Provide a SymbolContext for this StackFrame's current pc value.
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:294
const char * AsCString(const char *default_error_str="unknown error") const
Get the error string associated with the current error.
Definition Status.cpp:195
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)
Definition Stream.h:352
llvm::raw_ostream & AsRawOstream()
Returns a raw_ostream that forwards the data to this Stream object.
Definition Stream.h:400
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:65
void SetAddressByteSize(uint32_t addr_size)
Set the address size in bytes.
Definition Stream.cpp:209
size_t PutChar(char ch)
Definition Stream.cpp:131
void SetIndentLevel(unsigned level)
Set the current indentation level.
Definition Stream.cpp:190
void PutCStringColorHighlighted(llvm::StringRef text, std::optional< HighlightSettings > settings=std::nullopt)
Output a C string to the stream with color highlighting.
Definition Stream.cpp:75
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:198
void IndentMore(unsigned amount=2)
Increment the current indentation level.
Definition Stream.cpp:195
unsigned GetIndentLevel() const
Get the current indentation level.
Definition Stream.cpp:187
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:165
bool GetByteSizeIsValid() const
Definition Symbol.h:209
Address & GetAddressRef()
Definition Symbol.h:73
lldb::addr_t GetByteSize() const
Definition Symbol.cpp:431
ConstString GetDisplayName() const
Definition Symbol.cpp:169
uint64_t GetRawValue() const
Get the raw value of the symbol from the symbol table.
Definition Symbol.h:110
Symbol * SymbolAtIndex(size_t idx)
Definition Symtab.cpp:228
uint32_t AppendSymbolIndexesWithName(ConstString symbol_name, std::vector< uint32_t > &matches)
Definition Symtab.cpp:681
uint32_t AppendSymbolIndexesMatchingRegExAndType(const RegularExpression &regex, lldb::SymbolType symbol_type, std::vector< uint32_t > &indexes, Mangled::NamePreference name_preference=Mangled::ePreferDemangled)
Definition Symtab.cpp:758
lldb::TargetSP GetTargetAtIndex(uint32_t index) const
void SetSelectedTarget(uint32_t index)
bool DeleteTarget(lldb::TargetSP &target_sp)
Delete a Target object from the list.
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.
lldb::TargetSP GetSelectedTarget()
size_t GetNumTargets() const
bool GetUserSpecifiedTrapHandlerNames(Args &args) const
Definition Target.cpp:5017
Environment GetEnvironment() const
Definition Target.cpp:4671
void SetActionFromString(const std::string &strings)
Definition Target.cpp:3986
void SetActionFromStrings(const std::vector< std::string > &strings)
Definition Target.cpp:3990
Status SetScriptCallback(std::string class_name, StructuredData::ObjectSP extra_args_sp)
Definition Target.cpp:4031
void ModulesDidLoad(ModuleList &module_list)
Definition Target.cpp:1851
Module * GetExecutableModulePointer()
Definition Target.cpp:1533
StopHookSP CreateStopHook(StopHook::StopHookKind kind)
Add an empty stop hook to the Target's stop hook list, and returns a shared pointer to it in new_hook...
Definition Target.cpp:3041
PathMappingList & GetImageSearchPathList()
Definition Target.cpp:2593
std::shared_ptr< StopHook > StopHookSP
Definition Target.h:1460
void SymbolsDidLoad(ModuleList &module_list)
Definition Target.cpp:1871
size_t GetNumStopHooks() const
Definition Target.h:1496
void DumpSectionLoadList(Stream &s)
Definition Target.cpp:5241
const lldb::ProcessSP & GetProcessSP() const
Definition Target.cpp:306
lldb::ModuleSP GetOrCreateModule(const ModuleSpec &module_spec, bool notify, Status *error_ptr=nullptr)
Find a binary on the system and return its Module, or return an existing Module that is already in th...
Definition Target.cpp:2339
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:3056
bool ResolveLoadAddress(lldb::addr_t load_addr, Address &so_addr, uint32_t stop_id=SectionLoadHistory::eStopIDNow, bool allow_section_end=false)
Definition Target.cpp:3285
bool SetStopHookActiveStateByID(lldb::user_id_t uid, bool active_state)
Definition Target.cpp:3080
void SetAllStopHooksActiveState(bool active_state)
Definition Target.cpp:3091
StopHookSP GetStopHookAtIndex(size_t index)
Definition Target.h:1498
lldb::PlatformSP GetPlatform()
Definition Target.h:1510
const ModuleList & GetImages() const
Get accessor for the images for this process.
Definition Target.h:1014
const ArchSpec & GetArchitecture() const
Definition Target.h:1056
const std::string & GetLabel() const
Definition Target.h:603
lldb::ProcessSP CalculateProcess() override
Definition Target.cpp:2582
bool SetSectionLoadAddress(const lldb::SectionSP &section, lldb::addr_t load_addr, bool warn_multiple=false)
Definition Target.cpp:3296
bool RemoveStopHookByID(lldb::user_id_t uid)
Definition Target.cpp:3063
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:45
void SetName(llvm::StringRef name)
Definition ThreadSpec.h:49
void SetTID(lldb::tid_t tid)
Definition ThreadSpec.h:47
void SetQueueName(llvm::StringRef queue_name)
Definition ThreadSpec.h:51
uint32_t GetSize() const
Definition TypeList.cpp:60
bool Empty() const
Definition TypeList.h:37
TypeIterable Types()
Definition TypeList.h:44
lldb::TypeSP GetTypeAtIndex(uint32_t idx)
Definition TypeList.cpp:66
A class that contains all state required for type lookups.
Definition Type.h:104
This class tracks the state and results of a TypeQuery.
Definition Type.h:344
TypeMap & GetTypeMap()
Definition Type.h:386
void Dump(Stream &s) const
Definition UUID.cpp:68
std::string GetAsString(llvm::StringRef separator="-") const
Definition UUID.cpp:54
bool IsValid() const
Definition UUID.h:69
lldb::FuncUnwindersSP GetFuncUnwindersContainingAddress(const Address &addr, const SymbolContext &sc)
lldb::FuncUnwindersSP GetUncachedFuncUnwindersContainingAddress(const Address &addr, const SymbolContext &sc)
A collection of ValueObject values that.
void Append(const lldb::ValueObjectSP &val_obj_sp)
lldb::ValueObjectSP GetValueObjectAtIndex(size_t idx)
static lldb::ValueObjectSP Create(ExecutionContextScope *exe_scope, const lldb::VariableSP &var_sp)
lldb::VariableSP GetVariableAtIndex(size_t idx) const
static Status GetValuesForVariableExpressionPath(llvm::StringRef variable_expr_path, ExecutionContextScope *scope, GetVariableCallback callback, void *baton, VariableList &variable_list, ValueObjectList &valobj_list)
Definition Variable.cpp:326
#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:332
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
const char * toString(AppleArm64ExceptionClass EC)
@ 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::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:83
@ eArgTypeOldPathPrefix
@ eArgTypeNewPathPrefix
@ eArgTypeDirectoryName
std::shared_ptr< lldb_private::VariableList > VariableListSP
std::shared_ptr< lldb_private::UnwindPlan > UnwindPlanSP
std::shared_ptr< lldb_private::Variable > VariableSP
uint64_t user_id_t
Definition lldb-types.h:82
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:84
std::shared_ptr< lldb_private::Module > ModuleSP
@ eValueTypeVariableGlobal
globals variable
@ eValueTypeVariableLocal
function local variables
@ eValueTypeVariableArgument
function argument variables
@ eValueTypeVariableStatic
static variable
@ eValueTypeVariableThreadLocal
thread local storage variable
Used to build individual command argument lists.
Options used by Module::FindFunctions.
Definition Module.h:66
bool include_inlines
Include inlined functions.
Definition Module.h:70
bool include_symbols
Include the symbol table.
Definition Module.h:68
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)
Struct to store information for color highlighting in the stream.
Definition Stream.h:37
#define PATH_MAX