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