1 //===-- CommandObjectTarget.cpp ---------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "CommandObjectTarget.h"
13 #include "lldb/Core/Debugger.h"
14 #include "lldb/Core/IOHandler.h"
15 #include "lldb/Core/Module.h"
16 #include "lldb/Core/ModuleSpec.h"
17 #include "lldb/Core/Section.h"
18 #include "lldb/Core/State.h"
19 #include "lldb/Core/Timer.h"
20 #include "lldb/Core/ValueObjectVariable.h"
21 #include "lldb/DataFormatters/ValueObjectPrinter.h"
22 #include "lldb/Host/OptionParser.h"
23 #include "lldb/Host/StringConvert.h"
24 #include "lldb/Host/Symbols.h"
25 #include "lldb/Interpreter/Args.h"
26 #include "lldb/Interpreter/CommandInterpreter.h"
27 #include "lldb/Interpreter/CommandReturnObject.h"
28 #include "lldb/Interpreter/OptionGroupArchitecture.h"
29 #include "lldb/Interpreter/OptionGroupBoolean.h"
30 #include "lldb/Interpreter/OptionGroupFile.h"
31 #include "lldb/Interpreter/OptionGroupFormat.h"
32 #include "lldb/Interpreter/OptionGroupPlatform.h"
33 #include "lldb/Interpreter/OptionGroupString.h"
34 #include "lldb/Interpreter/OptionGroupUInt64.h"
35 #include "lldb/Interpreter/OptionGroupUUID.h"
36 #include "lldb/Interpreter/OptionGroupValueObjectDisplay.h"
37 #include "lldb/Interpreter/OptionGroupVariable.h"
38 #include "lldb/Interpreter/Options.h"
39 #include "lldb/Symbol/CompileUnit.h"
40 #include "lldb/Symbol/FuncUnwinders.h"
41 #include "lldb/Symbol/LineTable.h"
42 #include "lldb/Symbol/ObjectFile.h"
43 #include "lldb/Symbol/SymbolFile.h"
44 #include "lldb/Symbol/SymbolVendor.h"
45 #include "lldb/Symbol/UnwindPlan.h"
46 #include "lldb/Symbol/VariableList.h"
47 #include "lldb/Target/ABI.h"
48 #include "lldb/Target/Process.h"
49 #include "lldb/Target/SectionLoadList.h"
50 #include "lldb/Target/StackFrame.h"
51 #include "lldb/Target/Thread.h"
52 #include "lldb/Target/ThreadSpec.h"
54 #include "llvm/Support/FileSystem.h"
61 using namespace lldb_private;
63 static void DumpTargetInfo(uint32_t target_idx, Target *target,
64 const char *prefix_cstr,
65 bool show_stopped_process_status, Stream &strm) {
66 const ArchSpec &target_arch = target->GetArchitecture();
68 Module *exe_module = target->GetExecutableModulePointer();
69 char exe_path[PATH_MAX];
70 bool exe_valid = false;
72 exe_valid = exe_module->GetFileSpec().GetPath(exe_path, sizeof(exe_path));
75 ::strcpy(exe_path, "<none>");
77 strm.Printf("%starget #%u: %s", prefix_cstr ? prefix_cstr : "", target_idx,
80 uint32_t properties = 0;
81 if (target_arch.IsValid()) {
82 strm.Printf("%sarch=", properties++ > 0 ? ", " : " ( ");
83 target_arch.DumpTriple(strm);
86 PlatformSP platform_sp(target->GetPlatform());
88 strm.Printf("%splatform=%s", properties++ > 0 ? ", " : " ( ",
89 platform_sp->GetName().GetCString());
91 ProcessSP process_sp(target->GetProcessSP());
92 bool show_process_status = false;
94 lldb::pid_t pid = process_sp->GetID();
95 StateType state = process_sp->GetState();
96 if (show_stopped_process_status)
97 show_process_status = StateIsStoppedState(state, true);
98 const char *state_cstr = StateAsCString(state);
99 if (pid != LLDB_INVALID_PROCESS_ID)
100 strm.Printf("%spid=%" PRIu64, properties++ > 0 ? ", " : " ( ", pid);
101 strm.Printf("%sstate=%s", properties++ > 0 ? ", " : " ( ", state_cstr);
104 strm.PutCString(" )\n");
107 if (show_process_status) {
108 const bool only_threads_with_stop_reason = true;
109 const uint32_t start_frame = 0;
110 const uint32_t num_frames = 1;
111 const uint32_t num_frames_with_source = 1;
112 const bool stop_format = false;
113 process_sp->GetStatus(strm);
114 process_sp->GetThreadStatus(strm, only_threads_with_stop_reason,
115 start_frame, num_frames,
116 num_frames_with_source, stop_format);
120 static uint32_t DumpTargetList(TargetList &target_list,
121 bool show_stopped_process_status, Stream &strm) {
122 const uint32_t num_targets = target_list.GetNumTargets();
124 TargetSP selected_target_sp(target_list.GetSelectedTarget());
125 strm.PutCString("Current targets:\n");
126 for (uint32_t i = 0; i < num_targets; ++i) {
127 TargetSP target_sp(target_list.GetTargetAtIndex(i));
129 bool is_selected = target_sp.get() == selected_target_sp.get();
130 DumpTargetInfo(i, target_sp.get(), is_selected ? "* " : " ",
131 show_stopped_process_status, strm);
138 // TODO: Remove this once llvm can pretty-print time points
139 static void DumpTimePoint(llvm::sys::TimePoint<> tp, Stream &s, uint32_t width) {
140 #ifndef LLDB_DISABLE_POSIX
142 time_t time = llvm::sys::toTimeT(tp);
143 char *time_cstr = ::ctime_r(&time, time_buf);
145 char *newline = ::strpbrk(time_cstr, "\n\r");
149 s.Printf("%-*s", width, time_cstr);
151 s.PutCString(time_cstr);
152 } else if (width > 0)
153 s.Printf("%-*s", width, "");
157 #pragma mark CommandObjectTargetCreate
159 //-------------------------------------------------------------------------
161 //-------------------------------------------------------------------------
163 class CommandObjectTargetCreate : public CommandObjectParsed {
165 CommandObjectTargetCreate(CommandInterpreter &interpreter)
166 : CommandObjectParsed(
167 interpreter, "target create",
168 "Create a target using the argument as the main executable.",
170 m_option_group(), m_arch_option(),
171 m_core_file(LLDB_OPT_SET_1, false, "core", 'c', 0, eArgTypeFilename,
172 "Fullpath to a core file to use for this target."),
173 m_platform_path(LLDB_OPT_SET_1, false, "platform-path", 'P', 0,
175 "Path to the remote file to use for this target."),
176 m_symbol_file(LLDB_OPT_SET_1, false, "symfile", 's', 0,
177 eArgTypeFilename, "Fullpath to a stand alone debug "
178 "symbols file for when debug symbols "
179 "are not in the executable."),
181 LLDB_OPT_SET_1, false, "remote-file", 'r', 0, eArgTypeFilename,
182 "Fullpath to the file on the remote host if debugging remotely."),
183 m_add_dependents(LLDB_OPT_SET_1, false, "no-dependents", 'd',
184 "Don't load dependent files when creating the target, "
185 "just add the specified executable.",
187 CommandArgumentEntry arg;
188 CommandArgumentData file_arg;
190 // Define the first (and only) variant of this arg.
191 file_arg.arg_type = eArgTypeFilename;
192 file_arg.arg_repetition = eArgRepeatPlain;
194 // There is only one variant this argument could be; put it into the
196 arg.push_back(file_arg);
198 // Push the data for the first argument into the m_arguments vector.
199 m_arguments.push_back(arg);
201 m_option_group.Append(&m_arch_option, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
202 m_option_group.Append(&m_core_file, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
203 m_option_group.Append(&m_platform_path, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
204 m_option_group.Append(&m_symbol_file, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
205 m_option_group.Append(&m_remote_file, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
206 m_option_group.Append(&m_add_dependents, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
207 m_option_group.Finalize();
210 ~CommandObjectTargetCreate() override = default;
212 Options *GetOptions() override { return &m_option_group; }
214 int HandleArgumentCompletion(Args &input, int &cursor_index,
215 int &cursor_char_position,
216 OptionElementVector &opt_element_vector,
217 int match_start_point, int max_return_elements,
219 StringList &matches) override {
220 std::string completion_str(input.GetArgumentAtIndex(cursor_index));
221 completion_str.erase(cursor_char_position);
223 CommandCompletions::InvokeCommonCompletionCallbacks(
224 GetCommandInterpreter(), CommandCompletions::eDiskFileCompletion,
225 completion_str.c_str(), match_start_point, max_return_elements, nullptr,
226 word_complete, matches);
227 return matches.GetSize();
231 bool DoExecute(Args &command, CommandReturnObject &result) override {
232 const size_t argc = command.GetArgumentCount();
233 FileSpec core_file(m_core_file.GetOptionValue().GetCurrentValue());
234 FileSpec remote_file(m_remote_file.GetOptionValue().GetCurrentValue());
237 if (!core_file.Exists()) {
238 result.AppendErrorWithFormat("core file '%s' doesn't exist",
239 core_file.GetPath().c_str());
240 result.SetStatus(eReturnStatusFailed);
243 if (!core_file.Readable()) {
244 result.AppendErrorWithFormat("core file '%s' is not readable",
245 core_file.GetPath().c_str());
246 result.SetStatus(eReturnStatusFailed);
251 if (argc == 1 || core_file || remote_file) {
252 FileSpec symfile(m_symbol_file.GetOptionValue().GetCurrentValue());
254 if (symfile.Exists()) {
255 if (!symfile.Readable()) {
256 result.AppendErrorWithFormat("symbol file '%s' is not readable",
257 symfile.GetPath().c_str());
258 result.SetStatus(eReturnStatusFailed);
262 char symfile_path[PATH_MAX];
263 symfile.GetPath(symfile_path, sizeof(symfile_path));
264 result.AppendErrorWithFormat("invalid symbol file path '%s'",
266 result.SetStatus(eReturnStatusFailed);
271 const char *file_path = command.GetArgumentAtIndex(0);
272 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
273 Timer scoped_timer(func_cat, "(lldb) target create '%s'", file_path);
277 file_spec.SetFile(file_path, true);
279 bool must_set_platform_path = false;
281 Debugger &debugger = m_interpreter.GetDebugger();
284 llvm::StringRef arch_cstr = m_arch_option.GetArchitectureName();
285 const bool get_dependent_files =
286 m_add_dependents.GetOptionValue().GetCurrentValue();
287 Status error(debugger.GetTargetList().CreateTarget(
288 debugger, file_path, arch_cstr, get_dependent_files, nullptr,
292 // Only get the platform after we create the target because we might
294 // switched platforms depending on what the arguments were to
296 // we can't rely on the selected platform.
298 PlatformSP platform_sp = target_sp->GetPlatform();
302 // I have a remote file.. two possible cases
303 if (file_spec && file_spec.Exists()) {
304 // if the remote file does not exist, push it there
305 if (!platform_sp->GetFileExists(remote_file)) {
306 Status err = platform_sp->PutFile(file_spec, remote_file);
308 result.AppendError(err.AsCString());
309 result.SetStatus(eReturnStatusFailed);
314 // there is no local file and we need one
315 // in order to make the remote ---> local transfer we need a
317 // TODO: if the user has passed in a --platform argument, use it
318 // to fetch the right platform
321 "unable to perform remote debugging without a platform");
322 result.SetStatus(eReturnStatusFailed);
326 // copy the remote file to the local file
327 Status err = platform_sp->GetFile(remote_file, file_spec);
329 result.AppendError(err.AsCString());
330 result.SetStatus(eReturnStatusFailed);
334 // make up a local file
335 result.AppendError("remote --> local transfer without local "
336 "path is not implemented yet");
337 result.SetStatus(eReturnStatusFailed);
342 result.AppendError("no platform found for target");
343 result.SetStatus(eReturnStatusFailed);
348 if (symfile || remote_file) {
349 ModuleSP module_sp(target_sp->GetExecutableModule());
352 module_sp->SetSymbolFileFileSpec(symfile);
354 std::string remote_path = remote_file.GetPath();
355 target_sp->SetArg0(remote_path.c_str());
356 module_sp->SetPlatformFileSpec(remote_file);
361 debugger.GetTargetList().SetSelectedTarget(target_sp.get());
362 if (must_set_platform_path) {
363 ModuleSpec main_module_spec(file_spec);
364 ModuleSP module_sp = target_sp->GetSharedModule(main_module_spec);
366 module_sp->SetPlatformFileSpec(remote_file);
369 char core_path[PATH_MAX];
370 core_file.GetPath(core_path, sizeof(core_path));
371 if (core_file.Exists()) {
372 if (!core_file.Readable()) {
373 result.AppendMessageWithFormat(
374 "Core file '%s' is not readable.\n", core_path);
375 result.SetStatus(eReturnStatusFailed);
378 FileSpec core_file_dir;
379 core_file_dir.GetDirectory() = core_file.GetDirectory();
380 target_sp->GetExecutableSearchPaths().Append(core_file_dir);
382 ProcessSP process_sp(target_sp->CreateProcess(
383 m_interpreter.GetDebugger().GetListener(), llvm::StringRef(),
387 // Seems weird that we Launch a core file, but that is
389 error = process_sp->LoadCore();
393 error.AsCString("can't find plug-in for core file"));
394 result.SetStatus(eReturnStatusFailed);
397 result.AppendMessageWithFormat(
398 "Core file '%s' (%s) was loaded.\n", core_path,
399 target_sp->GetArchitecture().GetArchitectureName());
400 result.SetStatus(eReturnStatusSuccessFinishNoResult);
403 result.AppendErrorWithFormat(
404 "Unable to find process plug-in for core file '%s'\n",
406 result.SetStatus(eReturnStatusFailed);
409 result.AppendErrorWithFormat("Core file '%s' does not exist\n",
411 result.SetStatus(eReturnStatusFailed);
414 result.AppendMessageWithFormat(
415 "Current executable set to '%s' (%s).\n", file_path,
416 target_sp->GetArchitecture().GetArchitectureName());
417 result.SetStatus(eReturnStatusSuccessFinishNoResult);
420 result.AppendError(error.AsCString());
421 result.SetStatus(eReturnStatusFailed);
424 result.AppendErrorWithFormat("'%s' takes exactly one executable path "
425 "argument, or use the --core option.\n",
427 result.SetStatus(eReturnStatusFailed);
429 return result.Succeeded();
433 OptionGroupOptions m_option_group;
434 OptionGroupArchitecture m_arch_option;
435 OptionGroupFile m_core_file;
436 OptionGroupFile m_platform_path;
437 OptionGroupFile m_symbol_file;
438 OptionGroupFile m_remote_file;
439 OptionGroupBoolean m_add_dependents;
442 #pragma mark CommandObjectTargetList
444 //----------------------------------------------------------------------
446 //----------------------------------------------------------------------
448 class CommandObjectTargetList : public CommandObjectParsed {
450 CommandObjectTargetList(CommandInterpreter &interpreter)
451 : CommandObjectParsed(
452 interpreter, "target list",
453 "List all current targets in the current debug session.", nullptr) {
456 ~CommandObjectTargetList() override = default;
459 bool DoExecute(Args &args, CommandReturnObject &result) override {
460 if (args.GetArgumentCount() == 0) {
461 Stream &strm = result.GetOutputStream();
463 bool show_stopped_process_status = false;
464 if (DumpTargetList(m_interpreter.GetDebugger().GetTargetList(),
465 show_stopped_process_status, strm) == 0) {
466 strm.PutCString("No targets.\n");
468 result.SetStatus(eReturnStatusSuccessFinishResult);
470 result.AppendError("the 'target list' command takes no arguments\n");
471 result.SetStatus(eReturnStatusFailed);
473 return result.Succeeded();
477 #pragma mark CommandObjectTargetSelect
479 //----------------------------------------------------------------------
481 //----------------------------------------------------------------------
483 class CommandObjectTargetSelect : public CommandObjectParsed {
485 CommandObjectTargetSelect(CommandInterpreter &interpreter)
486 : CommandObjectParsed(
487 interpreter, "target select",
488 "Select a target as the current target by target index.", nullptr) {
491 ~CommandObjectTargetSelect() override = default;
494 bool DoExecute(Args &args, CommandReturnObject &result) override {
495 if (args.GetArgumentCount() == 1) {
496 bool success = false;
497 const char *target_idx_arg = args.GetArgumentAtIndex(0);
498 uint32_t target_idx =
499 StringConvert::ToUInt32(target_idx_arg, UINT32_MAX, 0, &success);
501 TargetList &target_list = m_interpreter.GetDebugger().GetTargetList();
502 const uint32_t num_targets = target_list.GetNumTargets();
503 if (target_idx < num_targets) {
504 TargetSP target_sp(target_list.GetTargetAtIndex(target_idx));
506 Stream &strm = result.GetOutputStream();
507 target_list.SetSelectedTarget(target_sp.get());
508 bool show_stopped_process_status = false;
509 DumpTargetList(target_list, show_stopped_process_status, strm);
510 result.SetStatus(eReturnStatusSuccessFinishResult);
512 result.AppendErrorWithFormat("target #%u is NULL in target list\n",
514 result.SetStatus(eReturnStatusFailed);
517 if (num_targets > 0) {
518 result.AppendErrorWithFormat(
519 "index %u is out of range, valid target indexes are 0 - %u\n",
520 target_idx, num_targets - 1);
522 result.AppendErrorWithFormat(
523 "index %u is out of range since there are no active targets\n",
526 result.SetStatus(eReturnStatusFailed);
529 result.AppendErrorWithFormat("invalid index string value '%s'\n",
531 result.SetStatus(eReturnStatusFailed);
535 "'target select' takes a single argument: a target index\n");
536 result.SetStatus(eReturnStatusFailed);
538 return result.Succeeded();
542 #pragma mark CommandObjectTargetSelect
544 //----------------------------------------------------------------------
546 //----------------------------------------------------------------------
548 class CommandObjectTargetDelete : public CommandObjectParsed {
550 CommandObjectTargetDelete(CommandInterpreter &interpreter)
551 : CommandObjectParsed(interpreter, "target delete",
552 "Delete one or more targets by target index.",
554 m_option_group(), m_all_option(LLDB_OPT_SET_1, false, "all", 'a',
555 "Delete all targets.", false, true),
557 LLDB_OPT_SET_1, false, "clean", 'c',
558 "Perform extra cleanup to minimize memory consumption after "
559 "deleting the target. "
560 "By default, LLDB will keep in memory any modules previously "
561 "loaded by the target as well "
562 "as all of its debug info. Specifying --clean will unload all of "
563 "these shared modules and "
564 "cause them to be reparsed again the next time the target is run",
566 m_option_group.Append(&m_all_option, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
567 m_option_group.Append(&m_cleanup_option, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
568 m_option_group.Finalize();
571 ~CommandObjectTargetDelete() override = default;
573 Options *GetOptions() override { return &m_option_group; }
576 bool DoExecute(Args &args, CommandReturnObject &result) override {
577 const size_t argc = args.GetArgumentCount();
578 std::vector<TargetSP> delete_target_list;
579 TargetList &target_list = m_interpreter.GetDebugger().GetTargetList();
582 if (m_all_option.GetOptionValue()) {
583 for (int i = 0; i < target_list.GetNumTargets(); ++i)
584 delete_target_list.push_back(target_list.GetTargetAtIndex(i));
585 } else if (argc > 0) {
586 const uint32_t num_targets = target_list.GetNumTargets();
587 // Bail out if don't have any targets.
588 if (num_targets == 0) {
589 result.AppendError("no targets to delete");
590 result.SetStatus(eReturnStatusFailed);
594 for (auto &entry : args.entries()) {
596 if (entry.ref.getAsInteger(0, target_idx)) {
597 result.AppendErrorWithFormat("invalid target index '%s'\n",
599 result.SetStatus(eReturnStatusFailed);
602 if (target_idx < num_targets) {
603 target_sp = target_list.GetTargetAtIndex(target_idx);
605 delete_target_list.push_back(target_sp);
610 result.AppendErrorWithFormat("target index %u is out of range, valid "
611 "target indexes are 0 - %u\n",
612 target_idx, num_targets - 1);
614 result.AppendErrorWithFormat(
615 "target index %u is out of range, the only valid index is 0\n",
618 result.SetStatus(eReturnStatusFailed);
622 target_sp = target_list.GetSelectedTarget();
624 result.AppendErrorWithFormat("no target is currently selected\n");
625 result.SetStatus(eReturnStatusFailed);
628 delete_target_list.push_back(target_sp);
631 const size_t num_targets_to_delete = delete_target_list.size();
632 for (size_t idx = 0; idx < num_targets_to_delete; ++idx) {
633 target_sp = delete_target_list[idx];
634 target_list.DeleteTarget(target_sp);
635 target_sp->Destroy();
637 // If "--clean" was specified, prune any orphaned shared modules from
638 // the global shared module list
639 if (m_cleanup_option.GetOptionValue()) {
640 const bool mandatory = true;
641 ModuleList::RemoveOrphanSharedModules(mandatory);
643 result.GetOutputStream().Printf("%u targets deleted.\n",
644 (uint32_t)num_targets_to_delete);
645 result.SetStatus(eReturnStatusSuccessFinishResult);
650 OptionGroupOptions m_option_group;
651 OptionGroupBoolean m_all_option;
652 OptionGroupBoolean m_cleanup_option;
655 #pragma mark CommandObjectTargetVariable
657 //----------------------------------------------------------------------
659 //----------------------------------------------------------------------
661 class CommandObjectTargetVariable : public CommandObjectParsed {
662 static const uint32_t SHORT_OPTION_FILE = 0x66696c65; // 'file'
663 static const uint32_t SHORT_OPTION_SHLB = 0x73686c62; // 'shlb'
666 CommandObjectTargetVariable(CommandInterpreter &interpreter)
667 : CommandObjectParsed(interpreter, "target variable",
668 "Read global variables for the current target, "
669 "before or while running a process.",
670 nullptr, eCommandRequiresTarget),
672 m_option_variable(false), // Don't include frame options
673 m_option_format(eFormatDefault),
674 m_option_compile_units(LLDB_OPT_SET_1, false, "file", SHORT_OPTION_FILE,
676 "A basename or fullpath to a file that contains "
677 "global variables. This option can be "
678 "specified multiple times."),
679 m_option_shared_libraries(
680 LLDB_OPT_SET_1, false, "shlib", SHORT_OPTION_SHLB, 0,
682 "A basename or fullpath to a shared library to use in the search "
684 "variables. This option can be specified multiple times."),
686 CommandArgumentEntry arg;
687 CommandArgumentData var_name_arg;
689 // Define the first (and only) variant of this arg.
690 var_name_arg.arg_type = eArgTypeVarName;
691 var_name_arg.arg_repetition = eArgRepeatPlus;
693 // There is only one variant this argument could be; put it into the
695 arg.push_back(var_name_arg);
697 // Push the data for the first argument into the m_arguments vector.
698 m_arguments.push_back(arg);
700 m_option_group.Append(&m_varobj_options, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
701 m_option_group.Append(&m_option_variable, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
702 m_option_group.Append(&m_option_format,
703 OptionGroupFormat::OPTION_GROUP_FORMAT |
704 OptionGroupFormat::OPTION_GROUP_GDB_FMT,
706 m_option_group.Append(&m_option_compile_units, LLDB_OPT_SET_ALL,
708 m_option_group.Append(&m_option_shared_libraries, LLDB_OPT_SET_ALL,
710 m_option_group.Finalize();
713 ~CommandObjectTargetVariable() override = default;
715 void DumpValueObject(Stream &s, VariableSP &var_sp, ValueObjectSP &valobj_sp,
716 const char *root_name) {
717 DumpValueObjectOptions options(m_varobj_options.GetAsDumpOptions());
719 if (!valobj_sp->GetTargetSP()->GetDisplayRuntimeSupportValues() &&
720 valobj_sp->IsRuntimeSupportValue())
723 switch (var_sp->GetScope()) {
724 case eValueTypeVariableGlobal:
725 if (m_option_variable.show_scope)
726 s.PutCString("GLOBAL: ");
729 case eValueTypeVariableStatic:
730 if (m_option_variable.show_scope)
731 s.PutCString("STATIC: ");
734 case eValueTypeVariableArgument:
735 if (m_option_variable.show_scope)
736 s.PutCString(" ARG: ");
739 case eValueTypeVariableLocal:
740 if (m_option_variable.show_scope)
741 s.PutCString(" LOCAL: ");
744 case eValueTypeVariableThreadLocal:
745 if (m_option_variable.show_scope)
746 s.PutCString("THREAD: ");
753 if (m_option_variable.show_decl) {
754 bool show_fullpaths = false;
755 bool show_module = true;
756 if (var_sp->DumpDeclaration(&s, show_fullpaths, show_module))
760 const Format format = m_option_format.GetFormat();
761 if (format != eFormatDefault)
762 options.SetFormat(format);
764 options.SetRootValueObjectName(root_name);
766 valobj_sp->Dump(s, options);
769 static size_t GetVariableCallback(void *baton, const char *name,
770 VariableList &variable_list) {
771 Target *target = static_cast<Target *>(baton);
773 return target->GetImages().FindGlobalVariables(ConstString(name), true,
774 UINT32_MAX, variable_list);
779 Options *GetOptions() override { return &m_option_group; }
782 void DumpGlobalVariableList(const ExecutionContext &exe_ctx,
783 const SymbolContext &sc,
784 const VariableList &variable_list, Stream &s) {
785 size_t count = variable_list.GetSize();
789 s.Printf("Global variables for %s in %s:\n",
790 sc.comp_unit->GetPath().c_str(),
791 sc.module_sp->GetFileSpec().GetPath().c_str());
793 s.Printf("Global variables for %s\n",
794 sc.module_sp->GetFileSpec().GetPath().c_str());
796 } else if (sc.comp_unit) {
797 s.Printf("Global variables for %s\n", sc.comp_unit->GetPath().c_str());
800 for (uint32_t i = 0; i < count; ++i) {
801 VariableSP var_sp(variable_list.GetVariableAtIndex(i));
803 ValueObjectSP valobj_sp(ValueObjectVariable::Create(
804 exe_ctx.GetBestExecutionContextScope(), var_sp));
807 DumpValueObject(s, var_sp, valobj_sp,
808 var_sp->GetName().GetCString());
814 bool DoExecute(Args &args, CommandReturnObject &result) override {
815 Target *target = m_exe_ctx.GetTargetPtr();
816 const size_t argc = args.GetArgumentCount();
817 Stream &s = result.GetOutputStream();
821 // TODO: Convert to entry-based iteration. Requires converting
823 for (size_t idx = 0; idx < argc; ++idx) {
824 VariableList variable_list;
825 ValueObjectList valobj_list;
827 const char *arg = args.GetArgumentAtIndex(idx);
829 bool use_var_name = false;
830 if (m_option_variable.use_regex) {
831 RegularExpression regex(llvm::StringRef::withNullAsEmpty(arg));
832 if (!regex.IsValid()) {
833 result.GetErrorStream().Printf(
834 "error: invalid regular expression: '%s'\n", arg);
835 result.SetStatus(eReturnStatusFailed);
839 matches = target->GetImages().FindGlobalVariables(
840 regex, true, UINT32_MAX, variable_list);
842 Status error(Variable::GetValuesForVariableExpressionPath(
843 arg, m_exe_ctx.GetBestExecutionContextScope(),
844 GetVariableCallback, target, variable_list, valobj_list));
845 matches = variable_list.GetSize();
849 result.GetErrorStream().Printf(
850 "error: can't find global variable '%s'\n", arg);
851 result.SetStatus(eReturnStatusFailed);
854 for (uint32_t global_idx = 0; global_idx < matches; ++global_idx) {
855 VariableSP var_sp(variable_list.GetVariableAtIndex(global_idx));
857 ValueObjectSP valobj_sp(
858 valobj_list.GetValueObjectAtIndex(global_idx));
860 valobj_sp = ValueObjectVariable::Create(
861 m_exe_ctx.GetBestExecutionContextScope(), var_sp);
864 DumpValueObject(s, var_sp, valobj_sp,
865 use_var_name ? var_sp->GetName().GetCString()
872 const FileSpecList &compile_units =
873 m_option_compile_units.GetOptionValue().GetCurrentValue();
874 const FileSpecList &shlibs =
875 m_option_shared_libraries.GetOptionValue().GetCurrentValue();
876 SymbolContextList sc_list;
877 const size_t num_compile_units = compile_units.GetSize();
878 const size_t num_shlibs = shlibs.GetSize();
879 if (num_compile_units == 0 && num_shlibs == 0) {
880 bool success = false;
881 StackFrame *frame = m_exe_ctx.GetFramePtr();
882 CompileUnit *comp_unit = nullptr;
884 SymbolContext sc = frame->GetSymbolContext(eSymbolContextCompUnit);
886 const bool can_create = true;
887 VariableListSP comp_unit_varlist_sp(
888 sc.comp_unit->GetVariableList(can_create));
889 if (comp_unit_varlist_sp) {
890 size_t count = comp_unit_varlist_sp->GetSize();
892 DumpGlobalVariableList(m_exe_ctx, sc, *comp_unit_varlist_sp, s);
901 result.AppendErrorWithFormat(
902 "no global variables in current compile unit: %s\n",
903 comp_unit->GetPath().c_str());
905 result.AppendErrorWithFormat(
906 "no debug information for frame %u\n",
907 frame->GetFrameIndex());
909 result.AppendError("'target variable' takes one or more global "
910 "variable names as arguments\n");
911 result.SetStatus(eReturnStatusFailed);
914 SymbolContextList sc_list;
915 const bool append = true;
916 // We have one or more compile unit or shlib
917 if (num_shlibs > 0) {
918 for (size_t shlib_idx = 0; shlib_idx < num_shlibs; ++shlib_idx) {
919 const FileSpec module_file(shlibs.GetFileSpecAtIndex(shlib_idx));
920 ModuleSpec module_spec(module_file);
923 target->GetImages().FindFirstModule(module_spec));
925 if (num_compile_units > 0) {
926 for (size_t cu_idx = 0; cu_idx < num_compile_units; ++cu_idx)
927 module_sp->FindCompileUnits(
928 compile_units.GetFileSpecAtIndex(cu_idx), append,
932 sc.module_sp = module_sp;
936 // Didn't find matching shlib/module in target...
937 result.AppendErrorWithFormat(
938 "target doesn't contain the specified shared library: %s\n",
939 module_file.GetPath().c_str());
943 // No shared libraries, we just want to find globals for the compile
944 // units files that were specified
945 for (size_t cu_idx = 0; cu_idx < num_compile_units; ++cu_idx)
946 target->GetImages().FindCompileUnits(
947 compile_units.GetFileSpecAtIndex(cu_idx), append, sc_list);
950 const uint32_t num_scs = sc_list.GetSize();
953 for (uint32_t sc_idx = 0; sc_idx < num_scs; ++sc_idx) {
954 if (sc_list.GetContextAtIndex(sc_idx, sc)) {
956 const bool can_create = true;
957 VariableListSP comp_unit_varlist_sp(
958 sc.comp_unit->GetVariableList(can_create));
959 if (comp_unit_varlist_sp)
960 DumpGlobalVariableList(m_exe_ctx, sc, *comp_unit_varlist_sp,
962 } else if (sc.module_sp) {
963 // Get all global variables for this module
964 lldb_private::RegularExpression all_globals_regex(
966 ".")); // Any global with at least one character
967 VariableList variable_list;
968 sc.module_sp->FindGlobalVariables(all_globals_regex, append,
969 UINT32_MAX, variable_list);
970 DumpGlobalVariableList(m_exe_ctx, sc, variable_list, s);
978 if (m_interpreter.TruncationWarningNecessary()) {
979 result.GetOutputStream().Printf(m_interpreter.TruncationWarningText(),
981 m_interpreter.TruncationWarningGiven();
984 return result.Succeeded();
987 OptionGroupOptions m_option_group;
988 OptionGroupVariable m_option_variable;
989 OptionGroupFormat m_option_format;
990 OptionGroupFileList m_option_compile_units;
991 OptionGroupFileList m_option_shared_libraries;
992 OptionGroupValueObjectDisplay m_varobj_options;
995 #pragma mark CommandObjectTargetModulesSearchPathsAdd
997 class CommandObjectTargetModulesSearchPathsAdd : public CommandObjectParsed {
999 CommandObjectTargetModulesSearchPathsAdd(CommandInterpreter &interpreter)
1000 : CommandObjectParsed(interpreter, "target modules search-paths add",
1001 "Add new image search paths substitution pairs to "
1002 "the current target.",
1004 CommandArgumentEntry arg;
1005 CommandArgumentData old_prefix_arg;
1006 CommandArgumentData new_prefix_arg;
1008 // Define the first variant of this arg pair.
1009 old_prefix_arg.arg_type = eArgTypeOldPathPrefix;
1010 old_prefix_arg.arg_repetition = eArgRepeatPairPlus;
1012 // Define the first variant of this arg pair.
1013 new_prefix_arg.arg_type = eArgTypeNewPathPrefix;
1014 new_prefix_arg.arg_repetition = eArgRepeatPairPlus;
1016 // There are two required arguments that must always occur together, i.e. an
1017 // argument "pair". Because they
1018 // must always occur together, they are treated as two variants of one
1019 // argument rather than two independent
1020 // arguments. Push them both into the first argument position for
1023 arg.push_back(old_prefix_arg);
1024 arg.push_back(new_prefix_arg);
1026 m_arguments.push_back(arg);
1029 ~CommandObjectTargetModulesSearchPathsAdd() override = default;
1032 bool DoExecute(Args &command, CommandReturnObject &result) override {
1033 Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
1035 const size_t argc = command.GetArgumentCount();
1037 result.AppendError("add requires an even number of arguments\n");
1038 result.SetStatus(eReturnStatusFailed);
1040 for (size_t i = 0; i < argc; i += 2) {
1041 const char *from = command.GetArgumentAtIndex(i);
1042 const char *to = command.GetArgumentAtIndex(i + 1);
1044 if (from[0] && to[0]) {
1045 Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST);
1047 log->Printf("target modules search path adding ImageSearchPath "
1048 "pair: '%s' -> '%s'",
1051 bool last_pair = ((argc - i) == 2);
1052 target->GetImageSearchPathList().Append(
1053 ConstString(from), ConstString(to),
1054 last_pair); // Notify if this is the last pair
1055 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1058 result.AppendError("<path-prefix> can't be empty\n");
1060 result.AppendError("<new-path-prefix> can't be empty\n");
1061 result.SetStatus(eReturnStatusFailed);
1066 result.AppendError("invalid target\n");
1067 result.SetStatus(eReturnStatusFailed);
1069 return result.Succeeded();
1073 #pragma mark CommandObjectTargetModulesSearchPathsClear
1075 class CommandObjectTargetModulesSearchPathsClear : public CommandObjectParsed {
1077 CommandObjectTargetModulesSearchPathsClear(CommandInterpreter &interpreter)
1078 : CommandObjectParsed(interpreter, "target modules search-paths clear",
1079 "Clear all current image search path substitution "
1080 "pairs from the current target.",
1081 "target modules search-paths clear") {}
1083 ~CommandObjectTargetModulesSearchPathsClear() override = default;
1086 bool DoExecute(Args &command, CommandReturnObject &result) override {
1087 Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
1090 target->GetImageSearchPathList().Clear(notify);
1091 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1093 result.AppendError("invalid target\n");
1094 result.SetStatus(eReturnStatusFailed);
1096 return result.Succeeded();
1100 #pragma mark CommandObjectTargetModulesSearchPathsInsert
1102 class CommandObjectTargetModulesSearchPathsInsert : public CommandObjectParsed {
1104 CommandObjectTargetModulesSearchPathsInsert(CommandInterpreter &interpreter)
1105 : CommandObjectParsed(interpreter, "target modules search-paths insert",
1106 "Insert a new image search path substitution pair "
1107 "into the current target at the specified index.",
1109 CommandArgumentEntry arg1;
1110 CommandArgumentEntry arg2;
1111 CommandArgumentData index_arg;
1112 CommandArgumentData old_prefix_arg;
1113 CommandArgumentData new_prefix_arg;
1115 // Define the first and only variant of this arg.
1116 index_arg.arg_type = eArgTypeIndex;
1117 index_arg.arg_repetition = eArgRepeatPlain;
1119 // Put the one and only variant into the first arg for m_arguments:
1120 arg1.push_back(index_arg);
1122 // Define the first variant of this arg pair.
1123 old_prefix_arg.arg_type = eArgTypeOldPathPrefix;
1124 old_prefix_arg.arg_repetition = eArgRepeatPairPlus;
1126 // Define the first variant of this arg pair.
1127 new_prefix_arg.arg_type = eArgTypeNewPathPrefix;
1128 new_prefix_arg.arg_repetition = eArgRepeatPairPlus;
1130 // There are two required arguments that must always occur together, i.e. an
1131 // argument "pair". Because they
1132 // must always occur together, they are treated as two variants of one
1133 // argument rather than two independent
1134 // arguments. Push them both into the same argument position for
1137 arg2.push_back(old_prefix_arg);
1138 arg2.push_back(new_prefix_arg);
1140 // Add arguments to m_arguments.
1141 m_arguments.push_back(arg1);
1142 m_arguments.push_back(arg2);
1145 ~CommandObjectTargetModulesSearchPathsInsert() override = default;
1148 bool DoExecute(Args &command, CommandReturnObject &result) override {
1149 Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
1151 size_t argc = command.GetArgumentCount();
1152 // check for at least 3 arguments and an odd number of parameters
1153 if (argc >= 3 && argc & 1) {
1154 bool success = false;
1156 uint32_t insert_idx = StringConvert::ToUInt32(
1157 command.GetArgumentAtIndex(0), UINT32_MAX, 0, &success);
1160 result.AppendErrorWithFormat(
1161 "<index> parameter is not an integer: '%s'.\n",
1162 command.GetArgumentAtIndex(0));
1163 result.SetStatus(eReturnStatusFailed);
1164 return result.Succeeded();
1167 // shift off the index
1169 argc = command.GetArgumentCount();
1171 for (uint32_t i = 0; i < argc; i += 2, ++insert_idx) {
1172 const char *from = command.GetArgumentAtIndex(i);
1173 const char *to = command.GetArgumentAtIndex(i + 1);
1175 if (from[0] && to[0]) {
1176 bool last_pair = ((argc - i) == 2);
1177 target->GetImageSearchPathList().Insert(
1178 ConstString(from), ConstString(to), insert_idx, last_pair);
1179 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1182 result.AppendError("<path-prefix> can't be empty\n");
1184 result.AppendError("<new-path-prefix> can't be empty\n");
1185 result.SetStatus(eReturnStatusFailed);
1190 result.AppendError("insert requires at least three arguments\n");
1191 result.SetStatus(eReturnStatusFailed);
1192 return result.Succeeded();
1196 result.AppendError("invalid target\n");
1197 result.SetStatus(eReturnStatusFailed);
1199 return result.Succeeded();
1203 #pragma mark CommandObjectTargetModulesSearchPathsList
1205 class CommandObjectTargetModulesSearchPathsList : public CommandObjectParsed {
1207 CommandObjectTargetModulesSearchPathsList(CommandInterpreter &interpreter)
1208 : CommandObjectParsed(interpreter, "target modules search-paths list",
1209 "List all current image search path substitution "
1210 "pairs in the current target.",
1211 "target modules search-paths list") {}
1213 ~CommandObjectTargetModulesSearchPathsList() override = default;
1216 bool DoExecute(Args &command, CommandReturnObject &result) override {
1217 Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
1219 if (command.GetArgumentCount() != 0) {
1220 result.AppendError("list takes no arguments\n");
1221 result.SetStatus(eReturnStatusFailed);
1222 return result.Succeeded();
1225 target->GetImageSearchPathList().Dump(&result.GetOutputStream());
1226 result.SetStatus(eReturnStatusSuccessFinishResult);
1228 result.AppendError("invalid target\n");
1229 result.SetStatus(eReturnStatusFailed);
1231 return result.Succeeded();
1235 #pragma mark CommandObjectTargetModulesSearchPathsQuery
1237 class CommandObjectTargetModulesSearchPathsQuery : public CommandObjectParsed {
1239 CommandObjectTargetModulesSearchPathsQuery(CommandInterpreter &interpreter)
1240 : CommandObjectParsed(
1241 interpreter, "target modules search-paths query",
1242 "Transform a path using the first applicable image search path.",
1244 CommandArgumentEntry arg;
1245 CommandArgumentData path_arg;
1247 // Define the first (and only) variant of this arg.
1248 path_arg.arg_type = eArgTypeDirectoryName;
1249 path_arg.arg_repetition = eArgRepeatPlain;
1251 // There is only one variant this argument could be; put it into the
1253 arg.push_back(path_arg);
1255 // Push the data for the first argument into the m_arguments vector.
1256 m_arguments.push_back(arg);
1259 ~CommandObjectTargetModulesSearchPathsQuery() override = default;
1262 bool DoExecute(Args &command, CommandReturnObject &result) override {
1263 Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
1265 if (command.GetArgumentCount() != 1) {
1266 result.AppendError("query requires one argument\n");
1267 result.SetStatus(eReturnStatusFailed);
1268 return result.Succeeded();
1271 ConstString orig(command.GetArgumentAtIndex(0));
1272 ConstString transformed;
1273 if (target->GetImageSearchPathList().RemapPath(orig, transformed))
1274 result.GetOutputStream().Printf("%s\n", transformed.GetCString());
1276 result.GetOutputStream().Printf("%s\n", orig.GetCString());
1278 result.SetStatus(eReturnStatusSuccessFinishResult);
1280 result.AppendError("invalid target\n");
1281 result.SetStatus(eReturnStatusFailed);
1283 return result.Succeeded();
1287 //----------------------------------------------------------------------
1288 // Static Helper functions
1289 //----------------------------------------------------------------------
1290 static void DumpModuleArchitecture(Stream &strm, Module *module,
1291 bool full_triple, uint32_t width) {
1293 StreamString arch_strm;
1296 module->GetArchitecture().DumpTriple(arch_strm);
1298 arch_strm.PutCString(module->GetArchitecture().GetArchitectureName());
1299 std::string arch_str = arch_strm.GetString();
1302 strm.Printf("%-*s", width, arch_str.c_str());
1304 strm.PutCString(arch_str);
1308 static void DumpModuleUUID(Stream &strm, Module *module) {
1309 if (module && module->GetUUID().IsValid())
1310 module->GetUUID().Dump(&strm);
1312 strm.PutCString(" ");
1315 static uint32_t DumpCompileUnitLineTable(CommandInterpreter &interpreter,
1316 Stream &strm, Module *module,
1317 const FileSpec &file_spec,
1318 bool load_addresses) {
1319 uint32_t num_matches = 0;
1321 SymbolContextList sc_list;
1322 num_matches = module->ResolveSymbolContextsForFileSpec(
1323 file_spec, 0, false, eSymbolContextCompUnit, sc_list);
1325 for (uint32_t i = 0; i < num_matches; ++i) {
1327 if (sc_list.GetContextAtIndex(i, sc)) {
1331 strm << "Line table for " << *static_cast<FileSpec *>(sc.comp_unit)
1332 << " in `" << module->GetFileSpec().GetFilename() << "\n";
1333 LineTable *line_table = sc.comp_unit->GetLineTable();
1335 line_table->GetDescription(
1336 &strm, interpreter.GetExecutionContext().GetTargetPtr(),
1337 lldb::eDescriptionLevelBrief);
1339 strm << "No line table";
1346 static void DumpFullpath(Stream &strm, const FileSpec *file_spec_ptr,
1348 if (file_spec_ptr) {
1350 std::string fullpath = file_spec_ptr->GetPath();
1351 strm.Printf("%-*s", width, fullpath.c_str());
1354 file_spec_ptr->Dump(&strm);
1358 // Keep the width spacing correct if things go wrong...
1360 strm.Printf("%-*s", width, "");
1363 static void DumpDirectory(Stream &strm, const FileSpec *file_spec_ptr,
1365 if (file_spec_ptr) {
1367 strm.Printf("%-*s", width, file_spec_ptr->GetDirectory().AsCString(""));
1369 file_spec_ptr->GetDirectory().Dump(&strm);
1372 // Keep the width spacing correct if things go wrong...
1374 strm.Printf("%-*s", width, "");
1377 static void DumpBasename(Stream &strm, const FileSpec *file_spec_ptr,
1379 if (file_spec_ptr) {
1381 strm.Printf("%-*s", width, file_spec_ptr->GetFilename().AsCString(""));
1383 file_spec_ptr->GetFilename().Dump(&strm);
1386 // Keep the width spacing correct if things go wrong...
1388 strm.Printf("%-*s", width, "");
1391 static size_t DumpModuleObjfileHeaders(Stream &strm, ModuleList &module_list) {
1392 size_t num_dumped = 0;
1393 std::lock_guard<std::recursive_mutex> guard(module_list.GetMutex());
1394 const size_t num_modules = module_list.GetSize();
1395 if (num_modules > 0) {
1396 strm.Printf("Dumping headers for %" PRIu64 " module(s).\n",
1397 static_cast<uint64_t>(num_modules));
1399 for (size_t image_idx = 0; image_idx < num_modules; ++image_idx) {
1400 Module *module = module_list.GetModulePointerAtIndexUnlocked(image_idx);
1402 if (num_dumped++ > 0) {
1406 ObjectFile *objfile = module->GetObjectFile();
1407 objfile->Dump(&strm);
1415 static void DumpModuleSymtab(CommandInterpreter &interpreter, Stream &strm,
1416 Module *module, SortOrder sort_order) {
1418 SymbolVendor *sym_vendor = module->GetSymbolVendor();
1420 Symtab *symtab = sym_vendor->GetSymtab();
1422 symtab->Dump(&strm, interpreter.GetExecutionContext().GetTargetPtr(),
1428 static void DumpModuleSections(CommandInterpreter &interpreter, Stream &strm,
1431 SectionList *section_list = module->GetSectionList();
1433 strm.Printf("Sections for '%s' (%s):\n",
1434 module->GetSpecificationDescription().c_str(),
1435 module->GetArchitecture().GetArchitectureName());
1437 section_list->Dump(&strm,
1438 interpreter.GetExecutionContext().GetTargetPtr(), true,
1445 static bool DumpModuleSymbolVendor(Stream &strm, Module *module) {
1447 SymbolVendor *symbol_vendor = module->GetSymbolVendor(true);
1448 if (symbol_vendor) {
1449 symbol_vendor->Dump(&strm);
1456 static void DumpAddress(ExecutionContextScope *exe_scope,
1457 const Address &so_addr, bool verbose, Stream &strm) {
1459 strm.Indent(" Address: ");
1460 so_addr.Dump(&strm, exe_scope, Address::DumpStyleModuleWithFileAddress);
1461 strm.PutCString(" (");
1462 so_addr.Dump(&strm, exe_scope, Address::DumpStyleSectionNameOffset);
1463 strm.PutCString(")\n");
1464 strm.Indent(" Summary: ");
1465 const uint32_t save_indent = strm.GetIndentLevel();
1466 strm.SetIndentLevel(save_indent + 13);
1467 so_addr.Dump(&strm, exe_scope, Address::DumpStyleResolvedDescription);
1468 strm.SetIndentLevel(save_indent);
1469 // Print out detailed address information when verbose is enabled
1472 so_addr.Dump(&strm, exe_scope, Address::DumpStyleDetailedSymbolContext);
1477 static bool LookupAddressInModule(CommandInterpreter &interpreter, Stream &strm,
1478 Module *module, uint32_t resolve_mask,
1479 lldb::addr_t raw_addr, lldb::addr_t offset,
1482 lldb::addr_t addr = raw_addr - offset;
1485 Target *target = interpreter.GetExecutionContext().GetTargetPtr();
1486 if (target && !target->GetSectionLoadList().IsEmpty()) {
1487 if (!target->GetSectionLoadList().ResolveLoadAddress(addr, so_addr))
1489 else if (so_addr.GetModule().get() != module)
1492 if (!module->ResolveFileAddress(addr, so_addr))
1496 ExecutionContextScope *exe_scope =
1497 interpreter.GetExecutionContext().GetBestExecutionContextScope();
1498 DumpAddress(exe_scope, so_addr, verbose, strm);
1499 // strm.IndentMore();
1500 // strm.Indent (" Address: ");
1501 // so_addr.Dump (&strm, exe_scope,
1502 // Address::DumpStyleModuleWithFileAddress);
1503 // strm.PutCString (" (");
1504 // so_addr.Dump (&strm, exe_scope,
1505 // Address::DumpStyleSectionNameOffset);
1506 // strm.PutCString (")\n");
1507 // strm.Indent (" Summary: ");
1508 // const uint32_t save_indent = strm.GetIndentLevel ();
1509 // strm.SetIndentLevel (save_indent + 13);
1510 // so_addr.Dump (&strm, exe_scope,
1511 // Address::DumpStyleResolvedDescription);
1512 // strm.SetIndentLevel (save_indent);
1513 // // Print out detailed address information when verbose is enabled
1517 // so_addr.Dump (&strm, exe_scope,
1518 // Address::DumpStyleDetailedSymbolContext);
1520 // strm.IndentLess();
1527 static uint32_t LookupSymbolInModule(CommandInterpreter &interpreter,
1528 Stream &strm, Module *module,
1529 const char *name, bool name_is_regex,
1534 SymbolVendor *sym_vendor = module->GetSymbolVendor();
1536 Symtab *symtab = sym_vendor->GetSymtab();
1538 std::vector<uint32_t> match_indexes;
1539 ConstString symbol_name(name);
1540 uint32_t num_matches = 0;
1541 if (name_is_regex) {
1542 RegularExpression name_regexp(symbol_name.GetStringRef());
1543 num_matches = symtab->AppendSymbolIndexesMatchingRegExAndType(
1544 name_regexp, eSymbolTypeAny, match_indexes);
1547 symtab->AppendSymbolIndexesWithName(symbol_name, match_indexes);
1550 if (num_matches > 0) {
1552 strm.Printf("%u symbols match %s'%s' in ", num_matches,
1553 name_is_regex ? "the regular expression " : "", name);
1554 DumpFullpath(strm, &module->GetFileSpec(), 0);
1555 strm.PutCString(":\n");
1557 for (uint32_t i = 0; i < num_matches; ++i) {
1558 Symbol *symbol = symtab->SymbolAtIndex(match_indexes[i]);
1559 if (symbol && symbol->ValueIsAddress()) {
1560 DumpAddress(interpreter.GetExecutionContext()
1561 .GetBestExecutionContextScope(),
1562 symbol->GetAddressRef(), verbose, strm);
1574 static void DumpSymbolContextList(ExecutionContextScope *exe_scope,
1575 Stream &strm, SymbolContextList &sc_list,
1579 const uint32_t num_matches = sc_list.GetSize();
1581 for (uint32_t i = 0; i < num_matches; ++i) {
1583 if (sc_list.GetContextAtIndex(i, sc)) {
1586 sc.GetAddressRange(eSymbolContextEverything, 0, true, range);
1588 DumpAddress(exe_scope, range.GetBaseAddress(), verbose, strm);
1594 static size_t LookupFunctionInModule(CommandInterpreter &interpreter,
1595 Stream &strm, Module *module,
1596 const char *name, bool name_is_regex,
1597 bool include_inlines, bool include_symbols,
1599 if (module && name && name[0]) {
1600 SymbolContextList sc_list;
1601 const bool append = true;
1602 size_t num_matches = 0;
1603 if (name_is_regex) {
1604 RegularExpression function_name_regex((llvm::StringRef(name)));
1605 num_matches = module->FindFunctions(function_name_regex, include_symbols,
1606 include_inlines, append, sc_list);
1608 ConstString function_name(name);
1609 num_matches = module->FindFunctions(
1610 function_name, nullptr, eFunctionNameTypeAuto, include_symbols,
1611 include_inlines, append, sc_list);
1616 strm.Printf("%" PRIu64 " match%s found in ", (uint64_t)num_matches,
1617 num_matches > 1 ? "es" : "");
1618 DumpFullpath(strm, &module->GetFileSpec(), 0);
1619 strm.PutCString(":\n");
1620 DumpSymbolContextList(
1621 interpreter.GetExecutionContext().GetBestExecutionContextScope(),
1622 strm, sc_list, verbose);
1629 static size_t LookupTypeInModule(CommandInterpreter &interpreter, Stream &strm,
1630 Module *module, const char *name_cstr,
1631 bool name_is_regex) {
1632 if (module && name_cstr && name_cstr[0]) {
1634 const uint32_t max_num_matches = UINT32_MAX;
1635 size_t num_matches = 0;
1636 bool name_is_fully_qualified = false;
1639 ConstString name(name_cstr);
1640 llvm::DenseSet<lldb_private::SymbolFile *> searched_symbol_files;
1642 module->FindTypes(sc, name, name_is_fully_qualified, max_num_matches,
1643 searched_symbol_files, type_list);
1647 strm.Printf("%" PRIu64 " match%s found in ", (uint64_t)num_matches,
1648 num_matches > 1 ? "es" : "");
1649 DumpFullpath(strm, &module->GetFileSpec(), 0);
1650 strm.PutCString(":\n");
1651 for (TypeSP type_sp : type_list.Types()) {
1653 // Resolve the clang type so that any forward references
1654 // to types that haven't yet been parsed will get parsed.
1655 type_sp->GetFullCompilerType();
1656 type_sp->GetDescription(&strm, eDescriptionLevelFull, true);
1657 // Print all typedef chains
1658 TypeSP typedef_type_sp(type_sp);
1659 TypeSP typedefed_type_sp(typedef_type_sp->GetTypedefType());
1660 while (typedefed_type_sp) {
1662 strm.Printf(" typedef '%s': ",
1663 typedef_type_sp->GetName().GetCString());
1664 typedefed_type_sp->GetFullCompilerType();
1665 typedefed_type_sp->GetDescription(&strm, eDescriptionLevelFull,
1667 typedef_type_sp = typedefed_type_sp;
1668 typedefed_type_sp = typedef_type_sp->GetTypedefType();
1679 static size_t LookupTypeHere(CommandInterpreter &interpreter, Stream &strm,
1680 const SymbolContext &sym_ctx,
1681 const char *name_cstr, bool name_is_regex) {
1682 if (!sym_ctx.module_sp)
1686 const uint32_t max_num_matches = UINT32_MAX;
1687 size_t num_matches = 1;
1688 bool name_is_fully_qualified = false;
1690 ConstString name(name_cstr);
1691 llvm::DenseSet<SymbolFile *> searched_symbol_files;
1692 num_matches = sym_ctx.module_sp->FindTypes(
1693 sym_ctx, name, name_is_fully_qualified, max_num_matches,
1694 searched_symbol_files, type_list);
1698 strm.PutCString("Best match found in ");
1699 DumpFullpath(strm, &sym_ctx.module_sp->GetFileSpec(), 0);
1700 strm.PutCString(":\n");
1702 TypeSP type_sp(type_list.GetTypeAtIndex(0));
1704 // Resolve the clang type so that any forward references
1705 // to types that haven't yet been parsed will get parsed.
1706 type_sp->GetFullCompilerType();
1707 type_sp->GetDescription(&strm, eDescriptionLevelFull, true);
1708 // Print all typedef chains
1709 TypeSP typedef_type_sp(type_sp);
1710 TypeSP typedefed_type_sp(typedef_type_sp->GetTypedefType());
1711 while (typedefed_type_sp) {
1713 strm.Printf(" typedef '%s': ",
1714 typedef_type_sp->GetName().GetCString());
1715 typedefed_type_sp->GetFullCompilerType();
1716 typedefed_type_sp->GetDescription(&strm, eDescriptionLevelFull, true);
1717 typedef_type_sp = typedefed_type_sp;
1718 typedefed_type_sp = typedef_type_sp->GetTypedefType();
1726 static uint32_t LookupFileAndLineInModule(CommandInterpreter &interpreter,
1727 Stream &strm, Module *module,
1728 const FileSpec &file_spec,
1729 uint32_t line, bool check_inlines,
1731 if (module && file_spec) {
1732 SymbolContextList sc_list;
1733 const uint32_t num_matches = module->ResolveSymbolContextsForFileSpec(
1734 file_spec, line, check_inlines, eSymbolContextEverything, sc_list);
1735 if (num_matches > 0) {
1737 strm.Printf("%u match%s found in ", num_matches,
1738 num_matches > 1 ? "es" : "");
1741 strm.Printf(":%u", line);
1743 DumpFullpath(strm, &module->GetFileSpec(), 0);
1744 strm.PutCString(":\n");
1745 DumpSymbolContextList(
1746 interpreter.GetExecutionContext().GetBestExecutionContextScope(),
1747 strm, sc_list, verbose);
1754 static size_t FindModulesByName(Target *target, const char *module_name,
1755 ModuleList &module_list,
1756 bool check_global_list) {
1757 FileSpec module_file_spec(module_name, false);
1758 ModuleSpec module_spec(module_file_spec);
1760 const size_t initial_size = module_list.GetSize();
1762 if (check_global_list) {
1763 // Check the global list
1764 std::lock_guard<std::recursive_mutex> guard(
1765 Module::GetAllocationModuleCollectionMutex());
1766 const size_t num_modules = Module::GetNumberAllocatedModules();
1768 for (size_t image_idx = 0; image_idx < num_modules; ++image_idx) {
1769 Module *module = Module::GetAllocatedModuleAtIndex(image_idx);
1772 if (module->MatchesModuleSpec(module_spec)) {
1773 module_sp = module->shared_from_this();
1774 module_list.AppendIfNeeded(module_sp);
1780 const size_t num_matches =
1781 target->GetImages().FindModules(module_spec, module_list);
1783 // Not found in our module list for our target, check the main
1784 // shared module list in case it is a extra file used somewhere
1786 if (num_matches == 0) {
1787 module_spec.GetArchitecture() = target->GetArchitecture();
1788 ModuleList::FindSharedModules(module_spec, module_list);
1791 ModuleList::FindSharedModules(module_spec, module_list);
1795 return module_list.GetSize() - initial_size;
1798 #pragma mark CommandObjectTargetModulesModuleAutoComplete
1800 //----------------------------------------------------------------------
1801 // A base command object class that can auto complete with module file
1803 //----------------------------------------------------------------------
1805 class CommandObjectTargetModulesModuleAutoComplete
1806 : public CommandObjectParsed {
1808 CommandObjectTargetModulesModuleAutoComplete(CommandInterpreter &interpreter,
1812 : CommandObjectParsed(interpreter, name, help, syntax) {
1813 CommandArgumentEntry arg;
1814 CommandArgumentData file_arg;
1816 // Define the first (and only) variant of this arg.
1817 file_arg.arg_type = eArgTypeFilename;
1818 file_arg.arg_repetition = eArgRepeatStar;
1820 // There is only one variant this argument could be; put it into the
1822 arg.push_back(file_arg);
1824 // Push the data for the first argument into the m_arguments vector.
1825 m_arguments.push_back(arg);
1828 ~CommandObjectTargetModulesModuleAutoComplete() override = default;
1830 int HandleArgumentCompletion(Args &input, int &cursor_index,
1831 int &cursor_char_position,
1832 OptionElementVector &opt_element_vector,
1833 int match_start_point, int max_return_elements,
1834 bool &word_complete,
1835 StringList &matches) override {
1836 // Arguments are the standard module completer.
1837 std::string completion_str(input.GetArgumentAtIndex(cursor_index));
1838 completion_str.erase(cursor_char_position);
1840 CommandCompletions::InvokeCommonCompletionCallbacks(
1841 GetCommandInterpreter(), CommandCompletions::eModuleCompletion,
1842 completion_str.c_str(), match_start_point, max_return_elements, nullptr,
1843 word_complete, matches);
1844 return matches.GetSize();
1848 #pragma mark CommandObjectTargetModulesSourceFileAutoComplete
1850 //----------------------------------------------------------------------
1851 // A base command object class that can auto complete with module source
1853 //----------------------------------------------------------------------
1855 class CommandObjectTargetModulesSourceFileAutoComplete
1856 : public CommandObjectParsed {
1858 CommandObjectTargetModulesSourceFileAutoComplete(
1859 CommandInterpreter &interpreter, const char *name, const char *help,
1860 const char *syntax, uint32_t flags)
1861 : CommandObjectParsed(interpreter, name, help, syntax, flags) {
1862 CommandArgumentEntry arg;
1863 CommandArgumentData source_file_arg;
1865 // Define the first (and only) variant of this arg.
1866 source_file_arg.arg_type = eArgTypeSourceFile;
1867 source_file_arg.arg_repetition = eArgRepeatPlus;
1869 // There is only one variant this argument could be; put it into the
1871 arg.push_back(source_file_arg);
1873 // Push the data for the first argument into the m_arguments vector.
1874 m_arguments.push_back(arg);
1877 ~CommandObjectTargetModulesSourceFileAutoComplete() override = default;
1879 int HandleArgumentCompletion(Args &input, int &cursor_index,
1880 int &cursor_char_position,
1881 OptionElementVector &opt_element_vector,
1882 int match_start_point, int max_return_elements,
1883 bool &word_complete,
1884 StringList &matches) override {
1885 // Arguments are the standard source file completer.
1886 std::string completion_str(input.GetArgumentAtIndex(cursor_index));
1887 completion_str.erase(cursor_char_position);
1889 CommandCompletions::InvokeCommonCompletionCallbacks(
1890 GetCommandInterpreter(), CommandCompletions::eSourceFileCompletion,
1891 completion_str.c_str(), match_start_point, max_return_elements, nullptr,
1892 word_complete, matches);
1893 return matches.GetSize();
1897 #pragma mark CommandObjectTargetModulesDumpObjfile
1899 class CommandObjectTargetModulesDumpObjfile
1900 : public CommandObjectTargetModulesModuleAutoComplete {
1902 CommandObjectTargetModulesDumpObjfile(CommandInterpreter &interpreter)
1903 : CommandObjectTargetModulesModuleAutoComplete(
1904 interpreter, "target modules dump objfile",
1905 "Dump the object file headers from one or more target modules.",
1908 ~CommandObjectTargetModulesDumpObjfile() override = default;
1911 bool DoExecute(Args &command, CommandReturnObject &result) override {
1912 Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
1913 if (target == nullptr) {
1914 result.AppendError("invalid target, create a debug target using the "
1915 "'target create' command");
1916 result.SetStatus(eReturnStatusFailed);
1920 uint32_t addr_byte_size = target->GetArchitecture().GetAddressByteSize();
1921 result.GetOutputStream().SetAddressByteSize(addr_byte_size);
1922 result.GetErrorStream().SetAddressByteSize(addr_byte_size);
1924 size_t num_dumped = 0;
1925 if (command.GetArgumentCount() == 0) {
1926 // Dump all headers for all modules images
1927 num_dumped = DumpModuleObjfileHeaders(result.GetOutputStream(),
1928 target->GetImages());
1929 if (num_dumped == 0) {
1930 result.AppendError("the target has no associated executable images");
1931 result.SetStatus(eReturnStatusFailed);
1934 // Find the modules that match the basename or full path.
1935 ModuleList module_list;
1936 const char *arg_cstr;
1937 for (int arg_idx = 0;
1938 (arg_cstr = command.GetArgumentAtIndex(arg_idx)) != nullptr;
1940 size_t num_matched =
1941 FindModulesByName(target, arg_cstr, module_list, true);
1942 if (num_matched == 0) {
1943 result.AppendWarningWithFormat(
1944 "Unable to find an image that matches '%s'.\n", arg_cstr);
1947 // Dump all the modules we found.
1949 DumpModuleObjfileHeaders(result.GetOutputStream(), module_list);
1952 if (num_dumped > 0) {
1953 result.SetStatus(eReturnStatusSuccessFinishResult);
1955 result.AppendError("no matching executable images found");
1956 result.SetStatus(eReturnStatusFailed);
1958 return result.Succeeded();
1962 #pragma mark CommandObjectTargetModulesDumpSymtab
1964 static OptionEnumValueElement g_sort_option_enumeration[4] = {
1965 {eSortOrderNone, "none",
1966 "No sorting, use the original symbol table order."},
1967 {eSortOrderByAddress, "address", "Sort output by symbol address."},
1968 {eSortOrderByName, "name", "Sort output by symbol name."},
1969 {0, nullptr, nullptr}};
1971 static OptionDefinition g_target_modules_dump_symtab_options[] = {
1973 { LLDB_OPT_SET_1, false, "sort", 's', OptionParser::eRequiredArgument, nullptr, g_sort_option_enumeration, 0, eArgTypeSortOrder, "Supply a sort order when dumping the symbol table." }
1977 class CommandObjectTargetModulesDumpSymtab
1978 : public CommandObjectTargetModulesModuleAutoComplete {
1980 CommandObjectTargetModulesDumpSymtab(CommandInterpreter &interpreter)
1981 : CommandObjectTargetModulesModuleAutoComplete(
1982 interpreter, "target modules dump symtab",
1983 "Dump the symbol table from one or more target modules.", nullptr),
1986 ~CommandObjectTargetModulesDumpSymtab() override = default;
1988 Options *GetOptions() override { return &m_options; }
1990 class CommandOptions : public Options {
1992 CommandOptions() : Options(), m_sort_order(eSortOrderNone) {}
1994 ~CommandOptions() override = default;
1996 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1997 ExecutionContext *execution_context) override {
1999 const int short_option = m_getopt_table[option_idx].val;
2001 switch (short_option) {
2003 m_sort_order = (SortOrder)Args::StringToOptionEnum(
2004 option_arg, GetDefinitions()[option_idx].enum_values,
2005 eSortOrderNone, error);
2009 error.SetErrorStringWithFormat("invalid short option character '%c'",
2016 void OptionParsingStarting(ExecutionContext *execution_context) override {
2017 m_sort_order = eSortOrderNone;
2020 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
2021 return llvm::makeArrayRef(g_target_modules_dump_symtab_options);
2024 SortOrder m_sort_order;
2028 bool DoExecute(Args &command, CommandReturnObject &result) override {
2029 Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
2030 if (target == nullptr) {
2031 result.AppendError("invalid target, create a debug target using the "
2032 "'target create' command");
2033 result.SetStatus(eReturnStatusFailed);
2036 uint32_t num_dumped = 0;
2038 uint32_t addr_byte_size = target->GetArchitecture().GetAddressByteSize();
2039 result.GetOutputStream().SetAddressByteSize(addr_byte_size);
2040 result.GetErrorStream().SetAddressByteSize(addr_byte_size);
2042 if (command.GetArgumentCount() == 0) {
2043 // Dump all sections for all modules images
2044 std::lock_guard<std::recursive_mutex> guard(
2045 target->GetImages().GetMutex());
2046 const size_t num_modules = target->GetImages().GetSize();
2047 if (num_modules > 0) {
2048 result.GetOutputStream().Printf("Dumping symbol table for %" PRIu64
2050 (uint64_t)num_modules);
2051 for (size_t image_idx = 0; image_idx < num_modules; ++image_idx) {
2052 if (num_dumped > 0) {
2053 result.GetOutputStream().EOL();
2054 result.GetOutputStream().EOL();
2058 m_interpreter, result.GetOutputStream(),
2059 target->GetImages().GetModulePointerAtIndexUnlocked(image_idx),
2060 m_options.m_sort_order);
2063 result.AppendError("the target has no associated executable images");
2064 result.SetStatus(eReturnStatusFailed);
2068 // Dump specified images (by basename or fullpath)
2069 const char *arg_cstr;
2070 for (int arg_idx = 0;
2071 (arg_cstr = command.GetArgumentAtIndex(arg_idx)) != nullptr;
2073 ModuleList module_list;
2074 const size_t num_matches =
2075 FindModulesByName(target, arg_cstr, module_list, true);
2076 if (num_matches > 0) {
2077 for (size_t i = 0; i < num_matches; ++i) {
2078 Module *module = module_list.GetModulePointerAtIndex(i);
2080 if (num_dumped > 0) {
2081 result.GetOutputStream().EOL();
2082 result.GetOutputStream().EOL();
2085 DumpModuleSymtab(m_interpreter, result.GetOutputStream(),
2086 module, m_options.m_sort_order);
2090 result.AppendWarningWithFormat(
2091 "Unable to find an image that matches '%s'.\n", arg_cstr);
2096 result.SetStatus(eReturnStatusSuccessFinishResult);
2098 result.AppendError("no matching executable images found");
2099 result.SetStatus(eReturnStatusFailed);
2102 return result.Succeeded();
2105 CommandOptions m_options;
2108 #pragma mark CommandObjectTargetModulesDumpSections
2110 //----------------------------------------------------------------------
2111 // Image section dumping command
2112 //----------------------------------------------------------------------
2114 class CommandObjectTargetModulesDumpSections
2115 : public CommandObjectTargetModulesModuleAutoComplete {
2117 CommandObjectTargetModulesDumpSections(CommandInterpreter &interpreter)
2118 : CommandObjectTargetModulesModuleAutoComplete(
2119 interpreter, "target modules dump sections",
2120 "Dump the sections from one or more target modules.",
2121 //"target modules dump sections [<file1> ...]")
2124 ~CommandObjectTargetModulesDumpSections() override = default;
2127 bool DoExecute(Args &command, CommandReturnObject &result) override {
2128 Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
2129 if (target == nullptr) {
2130 result.AppendError("invalid target, create a debug target using the "
2131 "'target create' command");
2132 result.SetStatus(eReturnStatusFailed);
2135 uint32_t num_dumped = 0;
2137 uint32_t addr_byte_size = target->GetArchitecture().GetAddressByteSize();
2138 result.GetOutputStream().SetAddressByteSize(addr_byte_size);
2139 result.GetErrorStream().SetAddressByteSize(addr_byte_size);
2141 if (command.GetArgumentCount() == 0) {
2142 // Dump all sections for all modules images
2143 const size_t num_modules = target->GetImages().GetSize();
2144 if (num_modules > 0) {
2145 result.GetOutputStream().Printf("Dumping sections for %" PRIu64
2147 (uint64_t)num_modules);
2148 for (size_t image_idx = 0; image_idx < num_modules; ++image_idx) {
2151 m_interpreter, result.GetOutputStream(),
2152 target->GetImages().GetModulePointerAtIndex(image_idx));
2155 result.AppendError("the target has no associated executable images");
2156 result.SetStatus(eReturnStatusFailed);
2160 // Dump specified images (by basename or fullpath)
2161 const char *arg_cstr;
2162 for (int arg_idx = 0;
2163 (arg_cstr = command.GetArgumentAtIndex(arg_idx)) != nullptr;
2165 ModuleList module_list;
2166 const size_t num_matches =
2167 FindModulesByName(target, arg_cstr, module_list, true);
2168 if (num_matches > 0) {
2169 for (size_t i = 0; i < num_matches; ++i) {
2170 Module *module = module_list.GetModulePointerAtIndex(i);
2173 DumpModuleSections(m_interpreter, result.GetOutputStream(),
2178 // Check the global list
2179 std::lock_guard<std::recursive_mutex> guard(
2180 Module::GetAllocationModuleCollectionMutex());
2182 result.AppendWarningWithFormat(
2183 "Unable to find an image that matches '%s'.\n", arg_cstr);
2189 result.SetStatus(eReturnStatusSuccessFinishResult);
2191 result.AppendError("no matching executable images found");
2192 result.SetStatus(eReturnStatusFailed);
2195 return result.Succeeded();
2199 #pragma mark CommandObjectTargetModulesDumpSymfile
2201 //----------------------------------------------------------------------
2202 // Image debug symbol dumping command
2203 //----------------------------------------------------------------------
2205 class CommandObjectTargetModulesDumpSymfile
2206 : public CommandObjectTargetModulesModuleAutoComplete {
2208 CommandObjectTargetModulesDumpSymfile(CommandInterpreter &interpreter)
2209 : CommandObjectTargetModulesModuleAutoComplete(
2210 interpreter, "target modules dump symfile",
2211 "Dump the debug symbol file for one or more target modules.",
2212 //"target modules dump symfile [<file1> ...]")
2215 ~CommandObjectTargetModulesDumpSymfile() override = default;
2218 bool DoExecute(Args &command, CommandReturnObject &result) override {
2219 Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
2220 if (target == nullptr) {
2221 result.AppendError("invalid target, create a debug target using the "
2222 "'target create' command");
2223 result.SetStatus(eReturnStatusFailed);
2226 uint32_t num_dumped = 0;
2228 uint32_t addr_byte_size = target->GetArchitecture().GetAddressByteSize();
2229 result.GetOutputStream().SetAddressByteSize(addr_byte_size);
2230 result.GetErrorStream().SetAddressByteSize(addr_byte_size);
2232 if (command.GetArgumentCount() == 0) {
2233 // Dump all sections for all modules images
2234 const ModuleList &target_modules = target->GetImages();
2235 std::lock_guard<std::recursive_mutex> guard(target_modules.GetMutex());
2236 const size_t num_modules = target_modules.GetSize();
2237 if (num_modules > 0) {
2238 result.GetOutputStream().Printf("Dumping debug symbols for %" PRIu64
2240 (uint64_t)num_modules);
2241 for (uint32_t image_idx = 0; image_idx < num_modules; ++image_idx) {
2242 if (DumpModuleSymbolVendor(
2243 result.GetOutputStream(),
2244 target_modules.GetModulePointerAtIndexUnlocked(image_idx)))
2248 result.AppendError("the target has no associated executable images");
2249 result.SetStatus(eReturnStatusFailed);
2253 // Dump specified images (by basename or fullpath)
2254 const char *arg_cstr;
2255 for (int arg_idx = 0;
2256 (arg_cstr = command.GetArgumentAtIndex(arg_idx)) != nullptr;
2258 ModuleList module_list;
2259 const size_t num_matches =
2260 FindModulesByName(target, arg_cstr, module_list, true);
2261 if (num_matches > 0) {
2262 for (size_t i = 0; i < num_matches; ++i) {
2263 Module *module = module_list.GetModulePointerAtIndex(i);
2265 if (DumpModuleSymbolVendor(result.GetOutputStream(), module))
2270 result.AppendWarningWithFormat(
2271 "Unable to find an image that matches '%s'.\n", arg_cstr);
2276 result.SetStatus(eReturnStatusSuccessFinishResult);
2278 result.AppendError("no matching executable images found");
2279 result.SetStatus(eReturnStatusFailed);
2282 return result.Succeeded();
2286 #pragma mark CommandObjectTargetModulesDumpLineTable
2288 //----------------------------------------------------------------------
2289 // Image debug line table dumping command
2290 //----------------------------------------------------------------------
2292 class CommandObjectTargetModulesDumpLineTable
2293 : public CommandObjectTargetModulesSourceFileAutoComplete {
2295 CommandObjectTargetModulesDumpLineTable(CommandInterpreter &interpreter)
2296 : CommandObjectTargetModulesSourceFileAutoComplete(
2297 interpreter, "target modules dump line-table",
2298 "Dump the line table for one or more compilation units.", nullptr,
2299 eCommandRequiresTarget) {}
2301 ~CommandObjectTargetModulesDumpLineTable() override = default;
2304 bool DoExecute(Args &command, CommandReturnObject &result) override {
2305 Target *target = m_exe_ctx.GetTargetPtr();
2306 uint32_t total_num_dumped = 0;
2308 uint32_t addr_byte_size = target->GetArchitecture().GetAddressByteSize();
2309 result.GetOutputStream().SetAddressByteSize(addr_byte_size);
2310 result.GetErrorStream().SetAddressByteSize(addr_byte_size);
2312 if (command.GetArgumentCount() == 0) {
2313 result.AppendError("file option must be specified.");
2314 result.SetStatus(eReturnStatusFailed);
2315 return result.Succeeded();
2317 // Dump specified images (by basename or fullpath)
2318 const char *arg_cstr;
2319 for (int arg_idx = 0;
2320 (arg_cstr = command.GetArgumentAtIndex(arg_idx)) != nullptr;
2322 FileSpec file_spec(arg_cstr, false);
2324 const ModuleList &target_modules = target->GetImages();
2325 std::lock_guard<std::recursive_mutex> guard(target_modules.GetMutex());
2326 const size_t num_modules = target_modules.GetSize();
2327 if (num_modules > 0) {
2328 uint32_t num_dumped = 0;
2329 for (uint32_t i = 0; i < num_modules; ++i) {
2330 if (DumpCompileUnitLineTable(
2331 m_interpreter, result.GetOutputStream(),
2332 target_modules.GetModulePointerAtIndexUnlocked(i),
2333 file_spec, m_exe_ctx.GetProcessPtr() &&
2334 m_exe_ctx.GetProcessRef().IsAlive()))
2337 if (num_dumped == 0)
2338 result.AppendWarningWithFormat(
2339 "No source filenames matched '%s'.\n", arg_cstr);
2341 total_num_dumped += num_dumped;
2346 if (total_num_dumped > 0)
2347 result.SetStatus(eReturnStatusSuccessFinishResult);
2349 result.AppendError("no source filenames matched any command arguments");
2350 result.SetStatus(eReturnStatusFailed);
2352 return result.Succeeded();
2356 #pragma mark CommandObjectTargetModulesDump
2358 //----------------------------------------------------------------------
2359 // Dump multi-word command for target modules
2360 //----------------------------------------------------------------------
2362 class CommandObjectTargetModulesDump : public CommandObjectMultiword {
2364 //------------------------------------------------------------------
2365 // Constructors and Destructors
2366 //------------------------------------------------------------------
2367 CommandObjectTargetModulesDump(CommandInterpreter &interpreter)
2368 : CommandObjectMultiword(interpreter, "target modules dump",
2369 "Commands for dumping information about one or "
2370 "more target modules.",
2371 "target modules dump "
2372 "[headers|symtab|sections|symfile|line-table] "
2373 "[<file1> <file2> ...]") {
2374 LoadSubCommand("objfile",
2376 new CommandObjectTargetModulesDumpObjfile(interpreter)));
2379 CommandObjectSP(new CommandObjectTargetModulesDumpSymtab(interpreter)));
2380 LoadSubCommand("sections",
2381 CommandObjectSP(new CommandObjectTargetModulesDumpSections(
2383 LoadSubCommand("symfile",
2385 new CommandObjectTargetModulesDumpSymfile(interpreter)));
2386 LoadSubCommand("line-table",
2387 CommandObjectSP(new CommandObjectTargetModulesDumpLineTable(
2391 ~CommandObjectTargetModulesDump() override = default;
2394 class CommandObjectTargetModulesAdd : public CommandObjectParsed {
2396 CommandObjectTargetModulesAdd(CommandInterpreter &interpreter)
2397 : CommandObjectParsed(interpreter, "target modules add",
2398 "Add a new module to the current target's modules.",
2399 "target modules add [<module>]"),
2401 m_symbol_file(LLDB_OPT_SET_1, false, "symfile", 's', 0,
2402 eArgTypeFilename, "Fullpath to a stand alone debug "
2403 "symbols file for when debug symbols "
2404 "are not in the executable.") {
2405 m_option_group.Append(&m_uuid_option_group, LLDB_OPT_SET_ALL,
2407 m_option_group.Append(&m_symbol_file, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
2408 m_option_group.Finalize();
2411 ~CommandObjectTargetModulesAdd() override = default;
2413 Options *GetOptions() override { return &m_option_group; }
2415 int HandleArgumentCompletion(Args &input, int &cursor_index,
2416 int &cursor_char_position,
2417 OptionElementVector &opt_element_vector,
2418 int match_start_point, int max_return_elements,
2419 bool &word_complete,
2420 StringList &matches) override {
2421 std::string completion_str(input.GetArgumentAtIndex(cursor_index));
2422 completion_str.erase(cursor_char_position);
2424 CommandCompletions::InvokeCommonCompletionCallbacks(
2425 GetCommandInterpreter(), CommandCompletions::eDiskFileCompletion,
2426 completion_str.c_str(), match_start_point, max_return_elements, nullptr,
2427 word_complete, matches);
2428 return matches.GetSize();
2432 OptionGroupOptions m_option_group;
2433 OptionGroupUUID m_uuid_option_group;
2434 OptionGroupFile m_symbol_file;
2436 bool DoExecute(Args &args, CommandReturnObject &result) override {
2437 Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
2438 if (target == nullptr) {
2439 result.AppendError("invalid target, create a debug target using the "
2440 "'target create' command");
2441 result.SetStatus(eReturnStatusFailed);
2446 const size_t argc = args.GetArgumentCount();
2448 if (m_uuid_option_group.GetOptionValue().OptionWasSet()) {
2449 // We are given a UUID only, go locate the file
2450 ModuleSpec module_spec;
2451 module_spec.GetUUID() =
2452 m_uuid_option_group.GetOptionValue().GetCurrentValue();
2453 if (m_symbol_file.GetOptionValue().OptionWasSet())
2454 module_spec.GetSymbolFileSpec() =
2455 m_symbol_file.GetOptionValue().GetCurrentValue();
2456 if (Symbols::DownloadObjectAndSymbolFile(module_spec)) {
2457 ModuleSP module_sp(target->GetSharedModule(module_spec));
2459 result.SetStatus(eReturnStatusSuccessFinishResult);
2463 module_spec.GetUUID().Dump(&strm);
2464 if (module_spec.GetFileSpec()) {
2465 if (module_spec.GetSymbolFileSpec()) {
2466 result.AppendErrorWithFormat(
2467 "Unable to create the executable or symbol file with "
2468 "UUID %s with path %s and symbol file %s",
2470 module_spec.GetFileSpec().GetPath().c_str(),
2471 module_spec.GetSymbolFileSpec().GetPath().c_str());
2473 result.AppendErrorWithFormat(
2474 "Unable to create the executable or symbol file with "
2475 "UUID %s with path %s",
2477 module_spec.GetFileSpec().GetPath().c_str());
2480 result.AppendErrorWithFormat("Unable to create the executable "
2481 "or symbol file with UUID %s",
2484 result.SetStatus(eReturnStatusFailed);
2489 module_spec.GetUUID().Dump(&strm);
2490 result.AppendErrorWithFormat(
2491 "Unable to locate the executable or symbol file with UUID %s",
2493 result.SetStatus(eReturnStatusFailed);
2498 "one or more executable image paths must be specified");
2499 result.SetStatus(eReturnStatusFailed);
2503 for (auto &entry : args.entries()) {
2504 if (entry.ref.empty())
2507 FileSpec file_spec(entry.ref, true);
2508 if (file_spec.Exists()) {
2509 ModuleSpec module_spec(file_spec);
2510 if (m_uuid_option_group.GetOptionValue().OptionWasSet())
2511 module_spec.GetUUID() =
2512 m_uuid_option_group.GetOptionValue().GetCurrentValue();
2513 if (m_symbol_file.GetOptionValue().OptionWasSet())
2514 module_spec.GetSymbolFileSpec() =
2515 m_symbol_file.GetOptionValue().GetCurrentValue();
2516 if (!module_spec.GetArchitecture().IsValid())
2517 module_spec.GetArchitecture() = target->GetArchitecture();
2519 ModuleSP module_sp(target->GetSharedModule(module_spec, &error));
2521 const char *error_cstr = error.AsCString();
2523 result.AppendError(error_cstr);
2525 result.AppendErrorWithFormat("unsupported module: %s",
2527 result.SetStatus(eReturnStatusFailed);
2532 result.SetStatus(eReturnStatusSuccessFinishResult);
2534 std::string resolved_path = file_spec.GetPath();
2535 result.SetStatus(eReturnStatusFailed);
2536 if (resolved_path != entry.ref) {
2537 result.AppendErrorWithFormat(
2538 "invalid module path '%s' with resolved path '%s'\n",
2539 entry.ref.str().c_str(), resolved_path.c_str());
2542 result.AppendErrorWithFormat("invalid module path '%s'\n",
2550 ProcessSP process = target->GetProcessSP();
2556 return result.Succeeded();
2560 class CommandObjectTargetModulesLoad
2561 : public CommandObjectTargetModulesModuleAutoComplete {
2563 CommandObjectTargetModulesLoad(CommandInterpreter &interpreter)
2564 : CommandObjectTargetModulesModuleAutoComplete(
2565 interpreter, "target modules load", "Set the load addresses for "
2566 "one or more sections in a "
2568 "target modules load [--file <module> --uuid <uuid>] <sect-name> "
2569 "<address> [<sect-name> <address> ....]"),
2571 m_file_option(LLDB_OPT_SET_1, false, "file", 'f', 0, eArgTypeName,
2572 "Fullpath or basename for module to load.", ""),
2573 m_load_option(LLDB_OPT_SET_1, false, "load", 'l',
2574 "Write file contents to the memory.", false, true),
2575 m_pc_option(LLDB_OPT_SET_1, false, "--set-pc-to-entry", 'p',
2576 "Set PC to the entry point."
2577 " Only applicable with '--load' option.",
2579 m_slide_option(LLDB_OPT_SET_1, false, "slide", 's', 0, eArgTypeOffset,
2580 "Set the load address for all sections to be the "
2581 "virtual address in the file plus the offset.",
2583 m_option_group.Append(&m_uuid_option_group, LLDB_OPT_SET_ALL,
2585 m_option_group.Append(&m_file_option, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
2586 m_option_group.Append(&m_load_option, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
2587 m_option_group.Append(&m_pc_option, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
2588 m_option_group.Append(&m_slide_option, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
2589 m_option_group.Finalize();
2592 ~CommandObjectTargetModulesLoad() override = default;
2594 Options *GetOptions() override { return &m_option_group; }
2597 bool DoExecute(Args &args, CommandReturnObject &result) override {
2598 Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
2599 const bool load = m_load_option.GetOptionValue().GetCurrentValue();
2600 const bool set_pc = m_pc_option.GetOptionValue().GetCurrentValue();
2601 if (target == nullptr) {
2602 result.AppendError("invalid target, create a debug target using the "
2603 "'target create' command");
2604 result.SetStatus(eReturnStatusFailed);
2607 const size_t argc = args.GetArgumentCount();
2608 ModuleSpec module_spec;
2609 bool search_using_module_spec = false;
2611 // Allow "load" option to work without --file or --uuid
2614 if (!m_file_option.GetOptionValue().OptionWasSet() &&
2615 !m_uuid_option_group.GetOptionValue().OptionWasSet()) {
2616 ModuleList &module_list = target->GetImages();
2617 if (module_list.GetSize() == 1) {
2618 search_using_module_spec = true;
2619 module_spec.GetFileSpec() =
2620 module_list.GetModuleAtIndex(0)->GetFileSpec();
2625 if (m_file_option.GetOptionValue().OptionWasSet()) {
2626 search_using_module_spec = true;
2627 const char *arg_cstr = m_file_option.GetOptionValue().GetCurrentValue();
2628 const bool use_global_module_list = true;
2629 ModuleList module_list;
2630 const size_t num_matches = FindModulesByName(
2631 target, arg_cstr, module_list, use_global_module_list);
2632 if (num_matches == 1) {
2633 module_spec.GetFileSpec() =
2634 module_list.GetModuleAtIndex(0)->GetFileSpec();
2635 } else if (num_matches > 1) {
2636 search_using_module_spec = false;
2637 result.AppendErrorWithFormat(
2638 "more than 1 module matched by name '%s'\n", arg_cstr);
2639 result.SetStatus(eReturnStatusFailed);
2641 search_using_module_spec = false;
2642 result.AppendErrorWithFormat("no object file for module '%s'\n",
2644 result.SetStatus(eReturnStatusFailed);
2648 if (m_uuid_option_group.GetOptionValue().OptionWasSet()) {
2649 search_using_module_spec = true;
2650 module_spec.GetUUID() =
2651 m_uuid_option_group.GetOptionValue().GetCurrentValue();
2654 if (search_using_module_spec) {
2655 ModuleList matching_modules;
2656 const size_t num_matches =
2657 target->GetImages().FindModules(module_spec, matching_modules);
2659 char path[PATH_MAX];
2660 if (num_matches == 1) {
2661 Module *module = matching_modules.GetModulePointerAtIndex(0);
2663 ObjectFile *objfile = module->GetObjectFile();
2665 SectionList *section_list = module->GetSectionList();
2667 bool changed = false;
2669 if (m_slide_option.GetOptionValue().OptionWasSet()) {
2670 const addr_t slide =
2671 m_slide_option.GetOptionValue().GetCurrentValue();
2672 const bool slide_is_offset = true;
2673 module->SetLoadAddress(*target, slide, slide_is_offset,
2676 result.AppendError("one or more section name + load "
2677 "address pair must be specified");
2678 result.SetStatus(eReturnStatusFailed);
2682 if (m_slide_option.GetOptionValue().OptionWasSet()) {
2683 result.AppendError("The \"--slide <offset>\" option can't "
2684 "be used in conjunction with setting "
2685 "section load addresses.\n");
2686 result.SetStatus(eReturnStatusFailed);
2690 for (size_t i = 0; i < argc; i += 2) {
2691 const char *sect_name = args.GetArgumentAtIndex(i);
2692 const char *load_addr_cstr = args.GetArgumentAtIndex(i + 1);
2693 if (sect_name && load_addr_cstr) {
2694 ConstString const_sect_name(sect_name);
2695 bool success = false;
2696 addr_t load_addr = StringConvert::ToUInt64(
2697 load_addr_cstr, LLDB_INVALID_ADDRESS, 0, &success);
2699 SectionSP section_sp(
2700 section_list->FindSectionByName(const_sect_name));
2702 if (section_sp->IsThreadSpecific()) {
2703 result.AppendErrorWithFormat(
2704 "thread specific sections are not yet "
2705 "supported (section '%s')\n",
2707 result.SetStatus(eReturnStatusFailed);
2710 if (target->GetSectionLoadList()
2711 .SetSectionLoadAddress(section_sp,
2714 result.AppendMessageWithFormat(
2715 "section '%s' loaded at 0x%" PRIx64 "\n",
2716 sect_name, load_addr);
2719 result.AppendErrorWithFormat("no section found that "
2720 "matches the section "
2723 result.SetStatus(eReturnStatusFailed);
2727 result.AppendErrorWithFormat(
2728 "invalid load address string '%s'\n",
2730 result.SetStatus(eReturnStatusFailed);
2735 result.AppendError("section names must be followed by "
2736 "a load address.\n");
2738 result.AppendError("one or more section name + load "
2739 "address pair must be specified.\n");
2740 result.SetStatus(eReturnStatusFailed);
2747 target->ModulesDidLoad(matching_modules);
2748 Process *process = m_exe_ctx.GetProcessPtr();
2753 Status error = module->LoadInMemory(*target, set_pc);
2755 result.AppendError(error.AsCString());
2760 module->GetFileSpec().GetPath(path, sizeof(path));
2761 result.AppendErrorWithFormat(
2762 "no sections in object file '%s'\n", path);
2763 result.SetStatus(eReturnStatusFailed);
2766 module->GetFileSpec().GetPath(path, sizeof(path));
2767 result.AppendErrorWithFormat("no object file for module '%s'\n",
2769 result.SetStatus(eReturnStatusFailed);
2772 FileSpec *module_spec_file = module_spec.GetFileSpecPtr();
2773 if (module_spec_file) {
2774 module_spec_file->GetPath(path, sizeof(path));
2775 result.AppendErrorWithFormat("invalid module '%s'.\n", path);
2777 result.AppendError("no module spec");
2778 result.SetStatus(eReturnStatusFailed);
2781 std::string uuid_str;
2783 if (module_spec.GetFileSpec())
2784 module_spec.GetFileSpec().GetPath(path, sizeof(path));
2788 if (module_spec.GetUUIDPtr())
2789 uuid_str = module_spec.GetUUID().GetAsString();
2790 if (num_matches > 1) {
2791 result.AppendErrorWithFormat(
2792 "multiple modules match%s%s%s%s:\n", path[0] ? " file=" : "",
2793 path, !uuid_str.empty() ? " uuid=" : "", uuid_str.c_str());
2794 for (size_t i = 0; i < num_matches; ++i) {
2795 if (matching_modules.GetModulePointerAtIndex(i)
2797 .GetPath(path, sizeof(path)))
2798 result.AppendMessageWithFormat("%s\n", path);
2801 result.AppendErrorWithFormat(
2802 "no modules were found that match%s%s%s%s.\n",
2803 path[0] ? " file=" : "", path,
2804 !uuid_str.empty() ? " uuid=" : "", uuid_str.c_str());
2806 result.SetStatus(eReturnStatusFailed);
2809 result.AppendError("either the \"--file <module>\" or the \"--uuid "
2810 "<uuid>\" option must be specified.\n");
2811 result.SetStatus(eReturnStatusFailed);
2815 return result.Succeeded();
2818 OptionGroupOptions m_option_group;
2819 OptionGroupUUID m_uuid_option_group;
2820 OptionGroupString m_file_option;
2821 OptionGroupBoolean m_load_option;
2822 OptionGroupBoolean m_pc_option;
2823 OptionGroupUInt64 m_slide_option;
2826 //----------------------------------------------------------------------
2827 // List images with associated information
2828 //----------------------------------------------------------------------
2830 static OptionDefinition g_target_modules_list_options[] = {
2832 { LLDB_OPT_SET_1, false, "address", 'a', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeAddressOrExpression, "Display the image at this address." },
2833 { LLDB_OPT_SET_1, false, "arch", 'A', OptionParser::eOptionalArgument, nullptr, nullptr, 0, eArgTypeWidth, "Display the architecture when listing images." },
2834 { LLDB_OPT_SET_1, false, "triple", 't', OptionParser::eOptionalArgument, nullptr, nullptr, 0, eArgTypeWidth, "Display the triple when listing images." },
2835 { LLDB_OPT_SET_1, false, "header", 'h', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Display the image header address as a load address if debugging, a file address otherwise." },
2836 { LLDB_OPT_SET_1, false, "offset", 'o', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Display the image header address offset from the header file address (the slide amount)." },
2837 { LLDB_OPT_SET_1, false, "uuid", 'u', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Display the UUID when listing images." },
2838 { LLDB_OPT_SET_1, false, "fullpath", 'f', OptionParser::eOptionalArgument, nullptr, nullptr, 0, eArgTypeWidth, "Display the fullpath to the image object file." },
2839 { LLDB_OPT_SET_1, false, "directory", 'd', OptionParser::eOptionalArgument, nullptr, nullptr, 0, eArgTypeWidth, "Display the directory with optional width for the image object file." },
2840 { LLDB_OPT_SET_1, false, "basename", 'b', OptionParser::eOptionalArgument, nullptr, nullptr, 0, eArgTypeWidth, "Display the basename with optional width for the image object file." },
2841 { LLDB_OPT_SET_1, false, "symfile", 's', OptionParser::eOptionalArgument, nullptr, nullptr, 0, eArgTypeWidth, "Display the fullpath to the image symbol file with optional width." },
2842 { LLDB_OPT_SET_1, false, "symfile-unique", 'S', OptionParser::eOptionalArgument, nullptr, nullptr, 0, eArgTypeWidth, "Display the symbol file with optional width only if it is different from the executable object file." },
2843 { LLDB_OPT_SET_1, false, "mod-time", 'm', OptionParser::eOptionalArgument, nullptr, nullptr, 0, eArgTypeWidth, "Display the modification time with optional width of the module." },
2844 { LLDB_OPT_SET_1, false, "ref-count", 'r', OptionParser::eOptionalArgument, nullptr, nullptr, 0, eArgTypeWidth, "Display the reference count if the module is still in the shared module cache." },
2845 { LLDB_OPT_SET_1, false, "pointer", 'p', OptionParser::eOptionalArgument, nullptr, nullptr, 0, eArgTypeNone, "Display the module pointer." },
2846 { LLDB_OPT_SET_1, false, "global", 'g', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Display the modules from the global module list, not just the current target." }
2850 class CommandObjectTargetModulesList : public CommandObjectParsed {
2852 class CommandOptions : public Options {
2855 : Options(), m_format_array(), m_use_global_module_list(false),
2856 m_module_addr(LLDB_INVALID_ADDRESS) {}
2858 ~CommandOptions() override = default;
2860 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
2861 ExecutionContext *execution_context) override {
2864 const int short_option = m_getopt_table[option_idx].val;
2865 if (short_option == 'g') {
2866 m_use_global_module_list = true;
2867 } else if (short_option == 'a') {
2868 m_module_addr = Args::StringToAddress(execution_context, option_arg,
2869 LLDB_INVALID_ADDRESS, &error);
2871 unsigned long width = 0;
2872 option_arg.getAsInteger(0, width);
2873 m_format_array.push_back(std::make_pair(short_option, width));
2878 void OptionParsingStarting(ExecutionContext *execution_context) override {
2879 m_format_array.clear();
2880 m_use_global_module_list = false;
2881 m_module_addr = LLDB_INVALID_ADDRESS;
2884 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
2885 return llvm::makeArrayRef(g_target_modules_list_options);
2888 // Instance variables to hold the values for command options.
2889 typedef std::vector<std::pair<char, uint32_t>> FormatWidthCollection;
2890 FormatWidthCollection m_format_array;
2891 bool m_use_global_module_list;
2892 lldb::addr_t m_module_addr;
2895 CommandObjectTargetModulesList(CommandInterpreter &interpreter)
2896 : CommandObjectParsed(
2897 interpreter, "target modules list",
2898 "List current executable and dependent shared library images.",
2899 "target modules list [<cmd-options>]"),
2902 ~CommandObjectTargetModulesList() override = default;
2904 Options *GetOptions() override { return &m_options; }
2907 bool DoExecute(Args &command, CommandReturnObject &result) override {
2908 Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
2909 const bool use_global_module_list = m_options.m_use_global_module_list;
2910 // Define a local module list here to ensure it lives longer than any
2912 // object which might lock its contents below (through the "module_list_ptr"
2914 ModuleList module_list;
2915 if (target == nullptr && !use_global_module_list) {
2916 result.AppendError("invalid target, create a debug target using the "
2917 "'target create' command");
2918 result.SetStatus(eReturnStatusFailed);
2922 uint32_t addr_byte_size =
2923 target->GetArchitecture().GetAddressByteSize();
2924 result.GetOutputStream().SetAddressByteSize(addr_byte_size);
2925 result.GetErrorStream().SetAddressByteSize(addr_byte_size);
2927 // Dump all sections for all modules images
2928 Stream &strm = result.GetOutputStream();
2930 if (m_options.m_module_addr != LLDB_INVALID_ADDRESS) {
2932 Address module_address;
2933 if (module_address.SetLoadAddress(m_options.m_module_addr, target)) {
2934 ModuleSP module_sp(module_address.GetModule());
2936 PrintModule(target, module_sp.get(), 0, strm);
2937 result.SetStatus(eReturnStatusSuccessFinishResult);
2939 result.AppendErrorWithFormat(
2940 "Couldn't find module matching address: 0x%" PRIx64 ".",
2941 m_options.m_module_addr);
2942 result.SetStatus(eReturnStatusFailed);
2945 result.AppendErrorWithFormat(
2946 "Couldn't find module containing address: 0x%" PRIx64 ".",
2947 m_options.m_module_addr);
2948 result.SetStatus(eReturnStatusFailed);
2952 "Can only look up modules by address with a valid target.");
2953 result.SetStatus(eReturnStatusFailed);
2955 return result.Succeeded();
2958 size_t num_modules = 0;
2960 // This locker will be locked on the mutex in module_list_ptr if it is
2962 // Otherwise it will lock the AllocationModuleCollectionMutex when
2964 // the global module list directly.
2965 std::unique_lock<std::recursive_mutex> guard(
2966 Module::GetAllocationModuleCollectionMutex(), std::defer_lock);
2968 const ModuleList *module_list_ptr = nullptr;
2969 const size_t argc = command.GetArgumentCount();
2971 if (use_global_module_list) {
2973 num_modules = Module::GetNumberAllocatedModules();
2975 module_list_ptr = &target->GetImages();
2978 // TODO: Convert to entry based iteration. Requires converting
2979 // FindModulesByName.
2980 for (size_t i = 0; i < argc; ++i) {
2981 // Dump specified images (by basename or fullpath)
2982 const char *arg_cstr = command.GetArgumentAtIndex(i);
2983 const size_t num_matches = FindModulesByName(
2984 target, arg_cstr, module_list, use_global_module_list);
2985 if (num_matches == 0) {
2987 result.AppendErrorWithFormat("no modules found that match '%s'",
2989 result.SetStatus(eReturnStatusFailed);
2995 module_list_ptr = &module_list;
2998 std::unique_lock<std::recursive_mutex> lock;
2999 if (module_list_ptr != nullptr) {
3001 std::unique_lock<std::recursive_mutex>(module_list_ptr->GetMutex());
3003 num_modules = module_list_ptr->GetSize();
3006 if (num_modules > 0) {
3007 for (uint32_t image_idx = 0; image_idx < num_modules; ++image_idx) {
3010 if (module_list_ptr) {
3011 module_sp = module_list_ptr->GetModuleAtIndexUnlocked(image_idx);
3012 module = module_sp.get();
3014 module = Module::GetAllocatedModuleAtIndex(image_idx);
3015 module_sp = module->shared_from_this();
3018 const size_t indent = strm.Printf("[%3u] ", image_idx);
3019 PrintModule(target, module, indent, strm);
3021 result.SetStatus(eReturnStatusSuccessFinishResult);
3024 if (use_global_module_list)
3026 "the global module list has no matching modules");
3028 result.AppendError("the target has no matching modules");
3030 if (use_global_module_list)
3031 result.AppendError("the global module list is empty");
3034 "the target has no associated executable images");
3036 result.SetStatus(eReturnStatusFailed);
3040 return result.Succeeded();
3043 void PrintModule(Target *target, Module *module, int indent, Stream &strm) {
3044 if (module == nullptr) {
3045 strm.PutCString("Null module");
3049 bool dump_object_name = false;
3050 if (m_options.m_format_array.empty()) {
3051 m_options.m_format_array.push_back(std::make_pair('u', 0));
3052 m_options.m_format_array.push_back(std::make_pair('h', 0));
3053 m_options.m_format_array.push_back(std::make_pair('f', 0));
3054 m_options.m_format_array.push_back(std::make_pair('S', 0));
3056 const size_t num_entries = m_options.m_format_array.size();
3057 bool print_space = false;
3058 for (size_t i = 0; i < num_entries; ++i) {
3062 const char format_char = m_options.m_format_array[i].first;
3063 uint32_t width = m_options.m_format_array[i].second;
3064 switch (format_char) {
3066 DumpModuleArchitecture(strm, module, false, width);
3070 DumpModuleArchitecture(strm, module, true, width);
3074 DumpFullpath(strm, &module->GetFileSpec(), width);
3075 dump_object_name = true;
3079 DumpDirectory(strm, &module->GetFileSpec(), width);
3083 DumpBasename(strm, &module->GetFileSpec(), width);
3084 dump_object_name = true;
3089 // Image header address
3091 uint32_t addr_nibble_width =
3092 target ? (target->GetArchitecture().GetAddressByteSize() * 2)
3095 ObjectFile *objfile = module->GetObjectFile();
3097 Address header_addr(objfile->GetHeaderAddress());
3098 if (header_addr.IsValid()) {
3099 if (target && !target->GetSectionLoadList().IsEmpty()) {
3100 lldb::addr_t header_load_addr =
3101 header_addr.GetLoadAddress(target);
3102 if (header_load_addr == LLDB_INVALID_ADDRESS) {
3103 header_addr.Dump(&strm, target,
3104 Address::DumpStyleModuleWithFileAddress,
3105 Address::DumpStyleFileAddress);
3107 if (format_char == 'o') {
3108 // Show the offset of slide for the image
3110 "0x%*.*" PRIx64, addr_nibble_width, addr_nibble_width,
3111 header_load_addr - header_addr.GetFileAddress());
3113 // Show the load address of the image
3114 strm.Printf("0x%*.*" PRIx64, addr_nibble_width,
3115 addr_nibble_width, header_load_addr);
3120 // The address was valid, but the image isn't loaded, output the
3121 // address in an appropriate format
3122 header_addr.Dump(&strm, target, Address::DumpStyleFileAddress);
3126 strm.Printf("%*s", addr_nibble_width + 2, "");
3131 size_t ref_count = 0;
3132 ModuleSP module_sp(module->shared_from_this());
3134 // Take one away to make sure we don't count our local "module_sp"
3135 ref_count = module_sp.use_count() - 1;
3138 strm.Printf("{%*" PRIu64 "}", width, (uint64_t)ref_count);
3140 strm.Printf("{%" PRIu64 "}", (uint64_t)ref_count);
3145 const SymbolVendor *symbol_vendor = module->GetSymbolVendor();
3146 if (symbol_vendor) {
3147 const FileSpec symfile_spec = symbol_vendor->GetMainFileSpec();
3148 if (format_char == 'S') {
3149 // Dump symbol file only if different from module file
3150 if (!symfile_spec || symfile_spec == module->GetFileSpec()) {
3151 print_space = false;
3154 // Add a newline and indent past the index
3155 strm.Printf("\n%*s", indent, "");
3157 DumpFullpath(strm, &symfile_spec, width);
3158 dump_object_name = true;
3161 strm.Printf("%.*s", width, "<NONE>");
3165 DumpTimePoint(module->GetModificationTime(), strm, width);
3169 strm.Printf("%p", static_cast<void *>(module));
3173 DumpModuleUUID(strm, module);
3180 if (dump_object_name) {
3181 const char *object_name = module->GetObjectName().GetCString();
3183 strm.Printf("(%s)", object_name);
3188 CommandOptions m_options;
3191 #pragma mark CommandObjectTargetModulesShowUnwind
3193 //----------------------------------------------------------------------
3194 // Lookup unwind information in images
3195 //----------------------------------------------------------------------
3197 static OptionDefinition g_target_modules_show_unwind_options[] = {
3199 { LLDB_OPT_SET_1, false, "name", 'n', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeFunctionName, "Show unwind instructions for a function or symbol name." },
3200 { LLDB_OPT_SET_2, false, "address", 'a', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeAddressOrExpression, "Show unwind instructions for a function or symbol containing an address" }
3204 class CommandObjectTargetModulesShowUnwind : public CommandObjectParsed {
3207 eLookupTypeInvalid = -1,
3208 eLookupTypeAddress = 0,
3210 eLookupTypeFunction,
3211 eLookupTypeFunctionOrSymbol,
3215 class CommandOptions : public Options {
3218 : Options(), m_type(eLookupTypeInvalid), m_str(),
3219 m_addr(LLDB_INVALID_ADDRESS) {}
3221 ~CommandOptions() override = default;
3223 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
3224 ExecutionContext *execution_context) override {
3227 const int short_option = m_getopt_table[option_idx].val;
3229 switch (short_option) {
3232 m_type = eLookupTypeAddress;
3233 m_addr = Args::StringToAddress(execution_context, option_arg,
3234 LLDB_INVALID_ADDRESS, &error);
3235 if (m_addr == LLDB_INVALID_ADDRESS)
3236 error.SetErrorStringWithFormat("invalid address string '%s'",
3237 option_arg.str().c_str());
3243 m_type = eLookupTypeFunctionOrSymbol;
3247 error.SetErrorStringWithFormat("unrecognized option %c.", short_option);
3254 void OptionParsingStarting(ExecutionContext *execution_context) override {
3255 m_type = eLookupTypeInvalid;
3257 m_addr = LLDB_INVALID_ADDRESS;
3260 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
3261 return llvm::makeArrayRef(g_target_modules_show_unwind_options);
3264 // Instance variables to hold the values for command options.
3266 int m_type; // Should be a eLookupTypeXXX enum after parsing options
3267 std::string m_str; // Holds name lookup
3268 lldb::addr_t m_addr; // Holds the address to lookup
3271 CommandObjectTargetModulesShowUnwind(CommandInterpreter &interpreter)
3272 : CommandObjectParsed(
3273 interpreter, "target modules show-unwind",
3274 "Show synthesized unwind instructions for a function.", nullptr,
3275 eCommandRequiresTarget | eCommandRequiresProcess |
3276 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused),
3279 ~CommandObjectTargetModulesShowUnwind() override = default;
3281 Options *GetOptions() override { return &m_options; }
3284 bool DoExecute(Args &command, CommandReturnObject &result) override {
3285 Target *target = m_exe_ctx.GetTargetPtr();
3286 Process *process = m_exe_ctx.GetProcessPtr();
3289 abi = process->GetABI().get();
3291 if (process == nullptr) {
3293 "You must have a process running to use this command.");
3294 result.SetStatus(eReturnStatusFailed);
3298 ThreadList threads(process->GetThreadList());
3299 if (threads.GetSize() == 0) {
3300 result.AppendError("The process must be paused to use this command.");
3301 result.SetStatus(eReturnStatusFailed);
3305 ThreadSP thread(threads.GetThreadAtIndex(0));
3307 result.AppendError("The process must be paused to use this command.");
3308 result.SetStatus(eReturnStatusFailed);
3312 SymbolContextList sc_list;
3314 if (m_options.m_type == eLookupTypeFunctionOrSymbol) {
3315 ConstString function_name(m_options.m_str.c_str());
3316 target->GetImages().FindFunctions(function_name, eFunctionNameTypeAuto,
3317 true, false, true, sc_list);
3318 } else if (m_options.m_type == eLookupTypeAddress && target) {
3320 if (target->GetSectionLoadList().ResolveLoadAddress(m_options.m_addr,
3323 ModuleSP module_sp(addr.GetModule());
3324 module_sp->ResolveSymbolContextForAddress(addr,
3325 eSymbolContextEverything, sc);
3326 if (sc.function || sc.symbol) {
3332 "address-expression or function name option must be specified.");
3333 result.SetStatus(eReturnStatusFailed);
3337 size_t num_matches = sc_list.GetSize();
3338 if (num_matches == 0) {
3339 result.AppendErrorWithFormat("no unwind data found that matches '%s'.",
3340 m_options.m_str.c_str());
3341 result.SetStatus(eReturnStatusFailed);
3345 for (uint32_t idx = 0; idx < num_matches; idx++) {
3347 sc_list.GetContextAtIndex(idx, sc);
3348 if (sc.symbol == nullptr && sc.function == nullptr)
3350 if (!sc.module_sp || sc.module_sp->GetObjectFile() == nullptr)
3353 if (!sc.GetAddressRange(eSymbolContextFunction | eSymbolContextSymbol, 0,
3356 if (!range.GetBaseAddress().IsValid())
3358 ConstString funcname(sc.GetFunctionName());
3359 if (funcname.IsEmpty())
3361 addr_t start_addr = range.GetBaseAddress().GetLoadAddress(target);
3363 start_addr = abi->FixCodeAddress(start_addr);
3365 FuncUnwindersSP func_unwinders_sp(
3366 sc.module_sp->GetObjectFile()
3368 .GetUncachedFuncUnwindersContainingAddress(start_addr, sc));
3369 if (!func_unwinders_sp)
3372 result.GetOutputStream().Printf(
3373 "UNWIND PLANS for %s`%s (start addr 0x%" PRIx64 ")\n\n",
3374 sc.module_sp->GetPlatformFileSpec().GetFilename().AsCString(),
3375 funcname.AsCString(), start_addr);
3377 UnwindPlanSP non_callsite_unwind_plan =
3378 func_unwinders_sp->GetUnwindPlanAtNonCallSite(*target, *thread, -1);
3379 if (non_callsite_unwind_plan) {
3380 result.GetOutputStream().Printf(
3381 "Asynchronous (not restricted to call-sites) UnwindPlan is '%s'\n",
3382 non_callsite_unwind_plan->GetSourceName().AsCString());
3384 UnwindPlanSP callsite_unwind_plan =
3385 func_unwinders_sp->GetUnwindPlanAtCallSite(*target, -1);
3386 if (callsite_unwind_plan) {
3387 result.GetOutputStream().Printf(
3388 "Synchronous (restricted to call-sites) UnwindPlan is '%s'\n",
3389 callsite_unwind_plan->GetSourceName().AsCString());
3391 UnwindPlanSP fast_unwind_plan =
3392 func_unwinders_sp->GetUnwindPlanFastUnwind(*target, *thread);
3393 if (fast_unwind_plan) {
3394 result.GetOutputStream().Printf(
3395 "Fast UnwindPlan is '%s'\n",
3396 fast_unwind_plan->GetSourceName().AsCString());
3399 result.GetOutputStream().Printf("\n");
3401 UnwindPlanSP assembly_sp =
3402 func_unwinders_sp->GetAssemblyUnwindPlan(*target, *thread, 0);
3404 result.GetOutputStream().Printf(
3405 "Assembly language inspection UnwindPlan:\n");
3406 assembly_sp->Dump(result.GetOutputStream(), thread.get(),
3407 LLDB_INVALID_ADDRESS);
3408 result.GetOutputStream().Printf("\n");
3411 UnwindPlanSP ehframe_sp =
3412 func_unwinders_sp->GetEHFrameUnwindPlan(*target, 0);
3414 result.GetOutputStream().Printf("eh_frame UnwindPlan:\n");
3415 ehframe_sp->Dump(result.GetOutputStream(), thread.get(),
3416 LLDB_INVALID_ADDRESS);
3417 result.GetOutputStream().Printf("\n");
3420 UnwindPlanSP ehframe_augmented_sp =
3421 func_unwinders_sp->GetEHFrameAugmentedUnwindPlan(*target, *thread, 0);
3422 if (ehframe_augmented_sp) {
3423 result.GetOutputStream().Printf("eh_frame augmented UnwindPlan:\n");
3424 ehframe_augmented_sp->Dump(result.GetOutputStream(), thread.get(),
3425 LLDB_INVALID_ADDRESS);
3426 result.GetOutputStream().Printf("\n");
3429 UnwindPlanSP arm_unwind_sp =
3430 func_unwinders_sp->GetArmUnwindUnwindPlan(*target, 0);
3431 if (arm_unwind_sp) {
3432 result.GetOutputStream().Printf("ARM.exidx unwind UnwindPlan:\n");
3433 arm_unwind_sp->Dump(result.GetOutputStream(), thread.get(),
3434 LLDB_INVALID_ADDRESS);
3435 result.GetOutputStream().Printf("\n");
3438 UnwindPlanSP compact_unwind_sp =
3439 func_unwinders_sp->GetCompactUnwindUnwindPlan(*target, 0);
3440 if (compact_unwind_sp) {
3441 result.GetOutputStream().Printf("Compact unwind UnwindPlan:\n");
3442 compact_unwind_sp->Dump(result.GetOutputStream(), thread.get(),
3443 LLDB_INVALID_ADDRESS);
3444 result.GetOutputStream().Printf("\n");
3447 if (fast_unwind_plan) {
3448 result.GetOutputStream().Printf("Fast UnwindPlan:\n");
3449 fast_unwind_plan->Dump(result.GetOutputStream(), thread.get(),
3450 LLDB_INVALID_ADDRESS);
3451 result.GetOutputStream().Printf("\n");
3454 ABISP abi_sp = process->GetABI();
3456 UnwindPlan arch_default(lldb::eRegisterKindGeneric);
3457 if (abi_sp->CreateDefaultUnwindPlan(arch_default)) {
3458 result.GetOutputStream().Printf("Arch default UnwindPlan:\n");
3459 arch_default.Dump(result.GetOutputStream(), thread.get(),
3460 LLDB_INVALID_ADDRESS);
3461 result.GetOutputStream().Printf("\n");
3464 UnwindPlan arch_entry(lldb::eRegisterKindGeneric);
3465 if (abi_sp->CreateFunctionEntryUnwindPlan(arch_entry)) {
3466 result.GetOutputStream().Printf(
3467 "Arch default at entry point UnwindPlan:\n");
3468 arch_entry.Dump(result.GetOutputStream(), thread.get(),
3469 LLDB_INVALID_ADDRESS);
3470 result.GetOutputStream().Printf("\n");
3474 result.GetOutputStream().Printf("\n");
3476 return result.Succeeded();
3479 CommandOptions m_options;
3482 //----------------------------------------------------------------------
3483 // Lookup information in images
3484 //----------------------------------------------------------------------
3486 static OptionDefinition g_target_modules_lookup_options[] = {
3488 { LLDB_OPT_SET_1, true, "address", 'a', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeAddressOrExpression, "Lookup an address in one or more target modules." },
3489 { LLDB_OPT_SET_1, false, "offset", 'o', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeOffset, "When looking up an address subtract <offset> from any addresses before doing the lookup." },
3490 /* FIXME: re-enable regex for types when the LookupTypeInModule actually uses the regex option: | LLDB_OPT_SET_6 */
3491 { LLDB_OPT_SET_2 | LLDB_OPT_SET_4 | LLDB_OPT_SET_5, false, "regex", 'r', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "The <name> argument for name lookups are regular expressions." },
3492 { LLDB_OPT_SET_2, true, "symbol", 's', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeSymbol, "Lookup a symbol by name in the symbol tables in one or more target modules." },
3493 { LLDB_OPT_SET_3, true, "file", 'f', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeFilename, "Lookup a file by fullpath or basename in one or more target modules." },
3494 { LLDB_OPT_SET_3, false, "line", 'l', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeLineNum, "Lookup a line number in a file (must be used in conjunction with --file)." },
3495 { LLDB_OPT_SET_FROM_TO(3,5), false, "no-inlines", 'i', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Ignore inline entries (must be used in conjunction with --file or --function)." },
3496 { LLDB_OPT_SET_4, true, "function", 'F', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeFunctionName, "Lookup a function by name in the debug symbols in one or more target modules." },
3497 { LLDB_OPT_SET_5, true, "name", 'n', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeFunctionOrSymbol, "Lookup a function or symbol by name in one or more target modules." },
3498 { LLDB_OPT_SET_6, true, "type", 't', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeName, "Lookup a type by name in the debug symbols in one or more target modules." },
3499 { LLDB_OPT_SET_ALL, false, "verbose", 'v', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Enable verbose lookup information." },
3500 { LLDB_OPT_SET_ALL, false, "all", 'A', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Print all matches, not just the best match, if a best match is available." },
3504 class CommandObjectTargetModulesLookup : public CommandObjectParsed {
3507 eLookupTypeInvalid = -1,
3508 eLookupTypeAddress = 0,
3510 eLookupTypeFileLine, // Line is optional
3511 eLookupTypeFunction,
3512 eLookupTypeFunctionOrSymbol,
3517 class CommandOptions : public Options {
3519 CommandOptions() : Options() { OptionParsingStarting(nullptr); }
3521 ~CommandOptions() override = default;
3523 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
3524 ExecutionContext *execution_context) override {
3527 const int short_option = m_getopt_table[option_idx].val;
3529 switch (short_option) {
3531 m_type = eLookupTypeAddress;
3532 m_addr = Args::StringToAddress(execution_context, option_arg,
3533 LLDB_INVALID_ADDRESS, &error);
3537 if (option_arg.getAsInteger(0, m_offset))
3538 error.SetErrorStringWithFormat("invalid offset string '%s'",
3539 option_arg.str().c_str());
3544 m_type = eLookupTypeSymbol;
3548 m_file.SetFile(option_arg, false);
3549 m_type = eLookupTypeFileLine;
3553 m_include_inlines = false;
3557 if (option_arg.getAsInteger(0, m_line_number))
3558 error.SetErrorStringWithFormat("invalid line number string '%s'",
3559 option_arg.str().c_str());
3560 else if (m_line_number == 0)
3561 error.SetErrorString("zero is an invalid line number");
3562 m_type = eLookupTypeFileLine;
3567 m_type = eLookupTypeFunction;
3572 m_type = eLookupTypeFunctionOrSymbol;
3577 m_type = eLookupTypeType;
3596 void OptionParsingStarting(ExecutionContext *execution_context) override {
3597 m_type = eLookupTypeInvalid;
3600 m_addr = LLDB_INVALID_ADDRESS;
3603 m_use_regex = false;
3604 m_include_inlines = true;
3606 m_print_all = false;
3609 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
3610 return llvm::makeArrayRef(g_target_modules_lookup_options);
3613 int m_type; // Should be a eLookupTypeXXX enum after parsing options
3614 std::string m_str; // Holds name lookup
3615 FileSpec m_file; // Files for file lookups
3616 lldb::addr_t m_addr; // Holds the address to lookup
3618 m_offset; // Subtract this offset from m_addr before doing lookups.
3619 uint32_t m_line_number; // Line number for file+line lookups
3620 bool m_use_regex; // Name lookups in m_str are regular expressions.
3621 bool m_include_inlines; // Check for inline entries when looking up by
3623 bool m_verbose; // Enable verbose lookup info
3624 bool m_print_all; // Print all matches, even in cases where there's a best
3628 CommandObjectTargetModulesLookup(CommandInterpreter &interpreter)
3629 : CommandObjectParsed(interpreter, "target modules lookup",
3630 "Look up information within executable and "
3631 "dependent shared library images.",
3632 nullptr, eCommandRequiresTarget),
3634 CommandArgumentEntry arg;
3635 CommandArgumentData file_arg;
3637 // Define the first (and only) variant of this arg.
3638 file_arg.arg_type = eArgTypeFilename;
3639 file_arg.arg_repetition = eArgRepeatStar;
3641 // There is only one variant this argument could be; put it into the
3643 arg.push_back(file_arg);
3645 // Push the data for the first argument into the m_arguments vector.
3646 m_arguments.push_back(arg);
3649 ~CommandObjectTargetModulesLookup() override = default;
3651 Options *GetOptions() override { return &m_options; }
3653 bool LookupHere(CommandInterpreter &interpreter, CommandReturnObject &result,
3654 bool &syntax_error) {
3655 switch (m_options.m_type) {
3656 case eLookupTypeAddress:
3657 case eLookupTypeFileLine:
3658 case eLookupTypeFunction:
3659 case eLookupTypeFunctionOrSymbol:
3660 case eLookupTypeSymbol:
3663 case eLookupTypeType:
3667 StackFrameSP frame = m_exe_ctx.GetFrameSP();
3672 const SymbolContext &sym_ctx(frame->GetSymbolContext(eSymbolContextModule));
3674 if (!sym_ctx.module_sp)
3677 switch (m_options.m_type) {
3680 case eLookupTypeType:
3681 if (!m_options.m_str.empty()) {
3682 if (LookupTypeHere(m_interpreter, result.GetOutputStream(), sym_ctx,
3683 m_options.m_str.c_str(), m_options.m_use_regex)) {
3684 result.SetStatus(eReturnStatusSuccessFinishResult);
3694 bool LookupInModule(CommandInterpreter &interpreter, Module *module,
3695 CommandReturnObject &result, bool &syntax_error) {
3696 switch (m_options.m_type) {
3697 case eLookupTypeAddress:
3698 if (m_options.m_addr != LLDB_INVALID_ADDRESS) {
3699 if (LookupAddressInModule(
3700 m_interpreter, result.GetOutputStream(), module,
3701 eSymbolContextEverything |
3702 (m_options.m_verbose
3703 ? static_cast<int>(eSymbolContextVariable)
3705 m_options.m_addr, m_options.m_offset, m_options.m_verbose)) {
3706 result.SetStatus(eReturnStatusSuccessFinishResult);
3712 case eLookupTypeSymbol:
3713 if (!m_options.m_str.empty()) {
3714 if (LookupSymbolInModule(m_interpreter, result.GetOutputStream(),
3715 module, m_options.m_str.c_str(),
3716 m_options.m_use_regex, m_options.m_verbose)) {
3717 result.SetStatus(eReturnStatusSuccessFinishResult);
3723 case eLookupTypeFileLine:
3724 if (m_options.m_file) {
3725 if (LookupFileAndLineInModule(
3726 m_interpreter, result.GetOutputStream(), module,
3727 m_options.m_file, m_options.m_line_number,
3728 m_options.m_include_inlines, m_options.m_verbose)) {
3729 result.SetStatus(eReturnStatusSuccessFinishResult);
3735 case eLookupTypeFunctionOrSymbol:
3736 case eLookupTypeFunction:
3737 if (!m_options.m_str.empty()) {
3738 if (LookupFunctionInModule(
3739 m_interpreter, result.GetOutputStream(), module,
3740 m_options.m_str.c_str(), m_options.m_use_regex,
3741 m_options.m_include_inlines,
3743 eLookupTypeFunctionOrSymbol, // include symbols
3744 m_options.m_verbose)) {
3745 result.SetStatus(eReturnStatusSuccessFinishResult);
3751 case eLookupTypeType:
3752 if (!m_options.m_str.empty()) {
3753 if (LookupTypeInModule(m_interpreter, result.GetOutputStream(), module,
3754 m_options.m_str.c_str(),
3755 m_options.m_use_regex)) {
3756 result.SetStatus(eReturnStatusSuccessFinishResult);
3763 m_options.GenerateOptionUsage(
3764 result.GetErrorStream(), this,
3765 GetCommandInterpreter().GetDebugger().GetTerminalWidth());
3766 syntax_error = true;
3770 result.SetStatus(eReturnStatusFailed);
3775 bool DoExecute(Args &command, CommandReturnObject &result) override {
3776 Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
3777 if (target == nullptr) {
3778 result.AppendError("invalid target, create a debug target using the "
3779 "'target create' command");
3780 result.SetStatus(eReturnStatusFailed);
3783 bool syntax_error = false;
3785 uint32_t num_successful_lookups = 0;
3786 uint32_t addr_byte_size = target->GetArchitecture().GetAddressByteSize();
3787 result.GetOutputStream().SetAddressByteSize(addr_byte_size);
3788 result.GetErrorStream().SetAddressByteSize(addr_byte_size);
3789 // Dump all sections for all modules images
3791 if (command.GetArgumentCount() == 0) {
3792 ModuleSP current_module;
3794 // Where it is possible to look in the current symbol context
3795 // first, try that. If this search was successful and --all
3796 // was not passed, don't print anything else.
3797 if (LookupHere(m_interpreter, result, syntax_error)) {
3798 result.GetOutputStream().EOL();
3799 num_successful_lookups++;
3800 if (!m_options.m_print_all) {
3801 result.SetStatus(eReturnStatusSuccessFinishResult);
3802 return result.Succeeded();
3806 // Dump all sections for all other modules
3808 const ModuleList &target_modules = target->GetImages();
3809 std::lock_guard<std::recursive_mutex> guard(target_modules.GetMutex());
3810 const size_t num_modules = target_modules.GetSize();
3811 if (num_modules > 0) {
3812 for (i = 0; i < num_modules && !syntax_error; ++i) {
3813 Module *module_pointer =
3814 target_modules.GetModulePointerAtIndexUnlocked(i);
3816 if (module_pointer != current_module.get() &&
3819 target_modules.GetModulePointerAtIndexUnlocked(i), result,
3821 result.GetOutputStream().EOL();
3822 num_successful_lookups++;
3826 result.AppendError("the target has no associated executable images");
3827 result.SetStatus(eReturnStatusFailed);
3831 // Dump specified images (by basename or fullpath)
3832 const char *arg_cstr;
3833 for (i = 0; (arg_cstr = command.GetArgumentAtIndex(i)) != nullptr &&
3836 ModuleList module_list;
3837 const size_t num_matches =
3838 FindModulesByName(target, arg_cstr, module_list, false);
3839 if (num_matches > 0) {
3840 for (size_t j = 0; j < num_matches; ++j) {
3841 Module *module = module_list.GetModulePointerAtIndex(j);
3843 if (LookupInModule(m_interpreter, module, result,
3845 result.GetOutputStream().EOL();
3846 num_successful_lookups++;
3851 result.AppendWarningWithFormat(
3852 "Unable to find an image that matches '%s'.\n", arg_cstr);
3856 if (num_successful_lookups > 0)
3857 result.SetStatus(eReturnStatusSuccessFinishResult);
3859 result.SetStatus(eReturnStatusFailed);
3861 return result.Succeeded();
3864 CommandOptions m_options;
3867 #pragma mark CommandObjectMultiwordImageSearchPaths
3869 //-------------------------------------------------------------------------
3870 // CommandObjectMultiwordImageSearchPaths
3871 //-------------------------------------------------------------------------
3873 class CommandObjectTargetModulesImageSearchPaths
3874 : public CommandObjectMultiword {
3876 CommandObjectTargetModulesImageSearchPaths(CommandInterpreter &interpreter)
3877 : CommandObjectMultiword(
3878 interpreter, "target modules search-paths",
3879 "Commands for managing module search paths for a target.",
3880 "target modules search-paths <subcommand> [<subcommand-options>]") {
3882 "add", CommandObjectSP(
3883 new CommandObjectTargetModulesSearchPathsAdd(interpreter)));
3885 "clear", CommandObjectSP(new CommandObjectTargetModulesSearchPathsClear(
3890 new CommandObjectTargetModulesSearchPathsInsert(interpreter)));
3892 "list", CommandObjectSP(new CommandObjectTargetModulesSearchPathsList(
3895 "query", CommandObjectSP(new CommandObjectTargetModulesSearchPathsQuery(
3899 ~CommandObjectTargetModulesImageSearchPaths() override = default;
3902 #pragma mark CommandObjectTargetModules
3904 //-------------------------------------------------------------------------
3905 // CommandObjectTargetModules
3906 //-------------------------------------------------------------------------
3908 class CommandObjectTargetModules : public CommandObjectMultiword {
3910 //------------------------------------------------------------------
3911 // Constructors and Destructors
3912 //------------------------------------------------------------------
3913 CommandObjectTargetModules(CommandInterpreter &interpreter)
3914 : CommandObjectMultiword(interpreter, "target modules",
3915 "Commands for accessing information for one or "
3916 "more target modules.",
3917 "target modules <sub-command> ...") {
3919 "add", CommandObjectSP(new CommandObjectTargetModulesAdd(interpreter)));
3920 LoadSubCommand("load", CommandObjectSP(new CommandObjectTargetModulesLoad(
3922 LoadSubCommand("dump", CommandObjectSP(new CommandObjectTargetModulesDump(
3924 LoadSubCommand("list", CommandObjectSP(new CommandObjectTargetModulesList(
3928 CommandObjectSP(new CommandObjectTargetModulesLookup(interpreter)));
3932 new CommandObjectTargetModulesImageSearchPaths(interpreter)));
3935 CommandObjectSP(new CommandObjectTargetModulesShowUnwind(interpreter)));
3938 ~CommandObjectTargetModules() override = default;
3941 //------------------------------------------------------------------
3942 // For CommandObjectTargetModules only
3943 //------------------------------------------------------------------
3944 DISALLOW_COPY_AND_ASSIGN(CommandObjectTargetModules);
3947 class CommandObjectTargetSymbolsAdd : public CommandObjectParsed {
3949 CommandObjectTargetSymbolsAdd(CommandInterpreter &interpreter)
3950 : CommandObjectParsed(
3951 interpreter, "target symbols add",
3952 "Add a debug symbol file to one of the target's current modules by "
3953 "specifying a path to a debug symbols file, or using the options "
3954 "to specify a module to download symbols for.",
3955 "target symbols add [<symfile>]", eCommandRequiresTarget),
3958 LLDB_OPT_SET_1, false, "shlib", 's',
3959 CommandCompletions::eModuleCompletion, eArgTypeShlibName,
3960 "Fullpath or basename for module to find debug symbols for."),
3961 m_current_frame_option(
3962 LLDB_OPT_SET_2, false, "frame", 'F',
3963 "Locate the debug symbols the currently selected frame.", false,
3967 m_option_group.Append(&m_uuid_option_group, LLDB_OPT_SET_ALL,
3969 m_option_group.Append(&m_file_option, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
3970 m_option_group.Append(&m_current_frame_option, LLDB_OPT_SET_2,
3972 m_option_group.Finalize();
3975 ~CommandObjectTargetSymbolsAdd() override = default;
3977 int HandleArgumentCompletion(Args &input, int &cursor_index,
3978 int &cursor_char_position,
3979 OptionElementVector &opt_element_vector,
3980 int match_start_point, int max_return_elements,
3981 bool &word_complete,
3982 StringList &matches) override {
3983 std::string completion_str(input.GetArgumentAtIndex(cursor_index));
3984 completion_str.erase(cursor_char_position);
3986 CommandCompletions::InvokeCommonCompletionCallbacks(
3987 GetCommandInterpreter(), CommandCompletions::eDiskFileCompletion,
3988 completion_str.c_str(), match_start_point, max_return_elements, nullptr,
3989 word_complete, matches);
3990 return matches.GetSize();
3993 Options *GetOptions() override { return &m_option_group; }
3996 bool AddModuleSymbols(Target *target, ModuleSpec &module_spec, bool &flush,
3997 CommandReturnObject &result) {
3998 const FileSpec &symbol_fspec = module_spec.GetSymbolFileSpec();
4000 char symfile_path[PATH_MAX];
4001 symbol_fspec.GetPath(symfile_path, sizeof(symfile_path));
4003 if (!module_spec.GetUUID().IsValid()) {
4004 if (!module_spec.GetFileSpec() && !module_spec.GetPlatformFileSpec())
4005 module_spec.GetFileSpec().GetFilename() = symbol_fspec.GetFilename();
4007 // We now have a module that represents a symbol file
4008 // that can be used for a module that might exist in the
4009 // current target, so we need to find that module in the
4011 ModuleList matching_module_list;
4013 size_t num_matches = 0;
4014 // First extract all module specs from the symbol file
4015 lldb_private::ModuleSpecList symfile_module_specs;
4016 if (ObjectFile::GetModuleSpecifications(module_spec.GetSymbolFileSpec(),
4017 0, 0, symfile_module_specs)) {
4018 // Now extract the module spec that matches the target architecture
4019 ModuleSpec target_arch_module_spec;
4020 ModuleSpec symfile_module_spec;
4021 target_arch_module_spec.GetArchitecture() = target->GetArchitecture();
4022 if (symfile_module_specs.FindMatchingModuleSpec(target_arch_module_spec,
4023 symfile_module_spec)) {
4024 // See if it has a UUID?
4025 if (symfile_module_spec.GetUUID().IsValid()) {
4026 // It has a UUID, look for this UUID in the target modules
4027 ModuleSpec symfile_uuid_module_spec;
4028 symfile_uuid_module_spec.GetUUID() = symfile_module_spec.GetUUID();
4029 num_matches = target->GetImages().FindModules(
4030 symfile_uuid_module_spec, matching_module_list);
4034 if (num_matches == 0) {
4035 // No matches yet, iterate through the module specs to find a UUID
4037 // we can match up to an image in our target
4038 const size_t num_symfile_module_specs =
4039 symfile_module_specs.GetSize();
4040 for (size_t i = 0; i < num_symfile_module_specs && num_matches == 0;
4042 if (symfile_module_specs.GetModuleSpecAtIndex(
4043 i, symfile_module_spec)) {
4044 if (symfile_module_spec.GetUUID().IsValid()) {
4045 // It has a UUID, look for this UUID in the target modules
4046 ModuleSpec symfile_uuid_module_spec;
4047 symfile_uuid_module_spec.GetUUID() =
4048 symfile_module_spec.GetUUID();
4049 num_matches = target->GetImages().FindModules(
4050 symfile_uuid_module_spec, matching_module_list);
4057 // Just try to match up the file by basename if we have no matches at this
4059 if (num_matches == 0)
4061 target->GetImages().FindModules(module_spec, matching_module_list);
4063 while (num_matches == 0) {
4064 ConstString filename_no_extension(
4065 module_spec.GetFileSpec().GetFileNameStrippingExtension());
4066 // Empty string returned, lets bail
4067 if (!filename_no_extension)
4070 // Check if there was no extension to strip and the basename is the same
4071 if (filename_no_extension == module_spec.GetFileSpec().GetFilename())
4074 // Replace basename with one less extension
4075 module_spec.GetFileSpec().GetFilename() = filename_no_extension;
4078 target->GetImages().FindModules(module_spec, matching_module_list);
4081 if (num_matches > 1) {
4082 result.AppendErrorWithFormat("multiple modules match symbol file '%s', "
4083 "use the --uuid option to resolve the "
4086 } else if (num_matches == 1) {
4087 ModuleSP module_sp(matching_module_list.GetModuleAtIndex(0));
4089 // The module has not yet created its symbol vendor, we can just
4090 // give the existing target module the symfile path to use for
4091 // when it decides to create it!
4092 module_sp->SetSymbolFileFileSpec(symbol_fspec);
4094 SymbolVendor *symbol_vendor =
4095 module_sp->GetSymbolVendor(true, &result.GetErrorStream());
4096 if (symbol_vendor) {
4097 SymbolFile *symbol_file = symbol_vendor->GetSymbolFile();
4100 ObjectFile *object_file = symbol_file->GetObjectFile();
4102 if (object_file && object_file->GetFileSpec() == symbol_fspec) {
4103 // Provide feedback that the symfile has been successfully added.
4104 const FileSpec &module_fs = module_sp->GetFileSpec();
4105 result.AppendMessageWithFormat(
4106 "symbol file '%s' has been added to '%s'\n", symfile_path,
4107 module_fs.GetPath().c_str());
4109 // Let clients know something changed in the module
4110 // if it is currently loaded
4111 ModuleList module_list;
4112 module_list.Append(module_sp);
4113 target->SymbolsDidLoad(module_list);
4115 // Make sure we load any scripting resources that may be embedded
4116 // in the debug info files in case the platform supports that.
4118 StreamString feedback_stream;
4119 module_sp->LoadScriptingResourceInTarget(target, error,
4121 if (error.Fail() && error.AsCString())
4122 result.AppendWarningWithFormat(
4123 "unable to load scripting data for module %s - error "
4125 module_sp->GetFileSpec()
4126 .GetFileNameStrippingExtension()
4129 else if (feedback_stream.GetSize())
4130 result.AppendWarningWithFormat("%s", feedback_stream.GetData());
4133 result.SetStatus(eReturnStatusSuccessFinishResult);
4138 // Clear the symbol file spec if anything went wrong
4139 module_sp->SetSymbolFileFileSpec(FileSpec());
4142 namespace fs = llvm::sys::fs;
4143 if (module_spec.GetUUID().IsValid()) {
4144 StreamString ss_symfile_uuid;
4145 module_spec.GetUUID().Dump(&ss_symfile_uuid);
4146 result.AppendErrorWithFormat(
4147 "symbol file '%s' (%s) does not match any existing module%s\n",
4148 symfile_path, ss_symfile_uuid.GetData(),
4149 !fs::is_regular_file(symbol_fspec.GetPath())
4150 ? "\n please specify the full path to the symbol file"
4153 result.AppendErrorWithFormat(
4154 "symbol file '%s' does not match any existing module%s\n",
4156 !fs::is_regular_file(symbol_fspec.GetPath())
4157 ? "\n please specify the full path to the symbol file"
4162 "one or more executable image paths must be specified");
4164 result.SetStatus(eReturnStatusFailed);
4168 bool DoExecute(Args &args, CommandReturnObject &result) override {
4169 Target *target = m_exe_ctx.GetTargetPtr();
4170 result.SetStatus(eReturnStatusFailed);
4172 ModuleSpec module_spec;
4173 const bool uuid_option_set =
4174 m_uuid_option_group.GetOptionValue().OptionWasSet();
4175 const bool file_option_set = m_file_option.GetOptionValue().OptionWasSet();
4176 const bool frame_option_set =
4177 m_current_frame_option.GetOptionValue().OptionWasSet();
4178 const size_t argc = args.GetArgumentCount();
4181 if (uuid_option_set || file_option_set || frame_option_set) {
4182 bool success = false;
4183 bool error_set = false;
4184 if (frame_option_set) {
4185 Process *process = m_exe_ctx.GetProcessPtr();
4187 const StateType process_state = process->GetState();
4188 if (StateIsStoppedState(process_state, true)) {
4189 StackFrame *frame = m_exe_ctx.GetFramePtr();
4191 ModuleSP frame_module_sp(
4192 frame->GetSymbolContext(eSymbolContextModule).module_sp);
4193 if (frame_module_sp) {
4194 if (frame_module_sp->GetPlatformFileSpec().Exists()) {
4195 module_spec.GetArchitecture() =
4196 frame_module_sp->GetArchitecture();
4197 module_spec.GetFileSpec() =
4198 frame_module_sp->GetPlatformFileSpec();
4200 module_spec.GetUUID() = frame_module_sp->GetUUID();
4201 success = module_spec.GetUUID().IsValid() ||
4202 module_spec.GetFileSpec();
4204 result.AppendError("frame has no module");
4208 result.AppendError("invalid current frame");
4212 result.AppendErrorWithFormat("process is not stopped: %s",
4213 StateAsCString(process_state));
4218 "a process must exist in order to use the --frame option");
4222 if (uuid_option_set) {
4223 module_spec.GetUUID() =
4224 m_uuid_option_group.GetOptionValue().GetCurrentValue();
4225 success |= module_spec.GetUUID().IsValid();
4226 } else if (file_option_set) {
4227 module_spec.GetFileSpec() =
4228 m_file_option.GetOptionValue().GetCurrentValue();
4230 target->GetImages().FindFirstModule(module_spec));
4232 module_spec.GetFileSpec() = module_sp->GetFileSpec();
4233 module_spec.GetPlatformFileSpec() =
4234 module_sp->GetPlatformFileSpec();
4235 module_spec.GetUUID() = module_sp->GetUUID();
4236 module_spec.GetArchitecture() = module_sp->GetArchitecture();
4238 module_spec.GetArchitecture() = target->GetArchitecture();
4240 success |= module_spec.GetUUID().IsValid() ||
4241 module_spec.GetFileSpec().Exists();
4246 if (Symbols::DownloadObjectAndSymbolFile(module_spec)) {
4247 if (module_spec.GetSymbolFileSpec())
4248 success = AddModuleSymbols(target, module_spec, flush, result);
4252 if (!success && !error_set) {
4253 StreamString error_strm;
4254 if (uuid_option_set) {
4255 error_strm.PutCString("unable to find debug symbols for UUID ");
4256 module_spec.GetUUID().Dump(&error_strm);
4257 } else if (file_option_set) {
4258 error_strm.PutCString(
4259 "unable to find debug symbols for the executable file ");
4260 error_strm << module_spec.GetFileSpec();
4261 } else if (frame_option_set) {
4262 error_strm.PutCString(
4263 "unable to find debug symbols for the current frame");
4265 result.AppendError(error_strm.GetString());
4268 result.AppendError("one or more symbol file paths must be specified, "
4269 "or options must be specified");
4272 if (uuid_option_set) {
4273 result.AppendError("specify either one or more paths to symbol files "
4274 "or use the --uuid option without arguments");
4275 } else if (file_option_set) {
4276 result.AppendError("specify either one or more paths to symbol files "
4277 "or use the --file option without arguments");
4278 } else if (frame_option_set) {
4279 result.AppendError("specify either one or more paths to symbol files "
4280 "or use the --frame option without arguments");
4282 PlatformSP platform_sp(target->GetPlatform());
4284 for (auto &entry : args.entries()) {
4285 if (!entry.ref.empty()) {
4286 module_spec.GetSymbolFileSpec().SetFile(entry.ref, true);
4288 FileSpec symfile_spec;
4290 ->ResolveSymbolFile(*target, module_spec, symfile_spec)
4292 module_spec.GetSymbolFileSpec() = symfile_spec;
4296 bool symfile_exists = module_spec.GetSymbolFileSpec().Exists();
4298 if (symfile_exists) {
4299 if (!AddModuleSymbols(target, module_spec, flush, result))
4302 std::string resolved_symfile_path =
4303 module_spec.GetSymbolFileSpec().GetPath();
4304 if (resolved_symfile_path != entry.ref) {
4305 result.AppendErrorWithFormat(
4306 "invalid module path '%s' with resolved path '%s'\n",
4307 entry.c_str(), resolved_symfile_path.c_str());
4310 result.AppendErrorWithFormat("invalid module path '%s'\n",
4320 Process *process = m_exe_ctx.GetProcessPtr();
4324 return result.Succeeded();
4327 OptionGroupOptions m_option_group;
4328 OptionGroupUUID m_uuid_option_group;
4329 OptionGroupFile m_file_option;
4330 OptionGroupBoolean m_current_frame_option;
4333 #pragma mark CommandObjectTargetSymbols
4335 //-------------------------------------------------------------------------
4336 // CommandObjectTargetSymbols
4337 //-------------------------------------------------------------------------
4339 class CommandObjectTargetSymbols : public CommandObjectMultiword {
4341 //------------------------------------------------------------------
4342 // Constructors and Destructors
4343 //------------------------------------------------------------------
4344 CommandObjectTargetSymbols(CommandInterpreter &interpreter)
4345 : CommandObjectMultiword(
4346 interpreter, "target symbols",
4347 "Commands for adding and managing debug symbol files.",
4348 "target symbols <sub-command> ...") {
4350 "add", CommandObjectSP(new CommandObjectTargetSymbolsAdd(interpreter)));
4353 ~CommandObjectTargetSymbols() override = default;
4356 //------------------------------------------------------------------
4357 // For CommandObjectTargetModules only
4358 //------------------------------------------------------------------
4359 DISALLOW_COPY_AND_ASSIGN(CommandObjectTargetSymbols);
4362 #pragma mark CommandObjectTargetStopHookAdd
4364 //-------------------------------------------------------------------------
4365 // CommandObjectTargetStopHookAdd
4366 //-------------------------------------------------------------------------
4368 static OptionDefinition g_target_stop_hook_add_options[] = {
4370 { LLDB_OPT_SET_ALL, false, "one-liner", 'o', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeOneLiner, "Specify a one-line breakpoint command inline. Be sure to surround it with quotes." },
4371 { LLDB_OPT_SET_ALL, false, "shlib", 's', OptionParser::eRequiredArgument, nullptr, nullptr, CommandCompletions::eModuleCompletion, eArgTypeShlibName, "Set the module within which the stop-hook is to be run." },
4372 { LLDB_OPT_SET_ALL, false, "thread-index", 'x', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeThreadIndex, "The stop hook is run only for the thread whose index matches this argument." },
4373 { LLDB_OPT_SET_ALL, false, "thread-id", 't', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeThreadID, "The stop hook is run only for the thread whose TID matches this argument." },
4374 { LLDB_OPT_SET_ALL, false, "thread-name", 'T', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeThreadName, "The stop hook is run only for the thread whose thread name matches this argument." },
4375 { LLDB_OPT_SET_ALL, false, "queue-name", 'q', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeQueueName, "The stop hook is run only for threads in the queue whose name is given by this argument." },
4376 { LLDB_OPT_SET_1, false, "file", 'f', OptionParser::eRequiredArgument, nullptr, nullptr, CommandCompletions::eSourceFileCompletion, eArgTypeFilename, "Specify the source file within which the stop-hook is to be run." },
4377 { LLDB_OPT_SET_1, false, "start-line", 'l', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeLineNum, "Set the start of the line range for which the stop-hook is to be run." },
4378 { LLDB_OPT_SET_1, false, "end-line", 'e', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeLineNum, "Set the end of the line range for which the stop-hook is to be run." },
4379 { LLDB_OPT_SET_2, false, "classname", 'c', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeClassName, "Specify the class within which the stop-hook is to be run." },
4380 { LLDB_OPT_SET_3, false, "name", 'n', OptionParser::eRequiredArgument, nullptr, nullptr, CommandCompletions::eSymbolCompletion, eArgTypeFunctionName, "Set the function name within which the stop hook will be run." },
4384 class CommandObjectTargetStopHookAdd : public CommandObjectParsed,
4385 public IOHandlerDelegateMultiline {
4387 class CommandOptions : public Options {
4390 : Options(), m_line_start(0), m_line_end(UINT_MAX),
4391 m_func_name_type_mask(eFunctionNameTypeAuto),
4392 m_sym_ctx_specified(false), m_thread_specified(false),
4393 m_use_one_liner(false), m_one_liner() {}
4395 ~CommandOptions() override = default;
4397 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
4398 return llvm::makeArrayRef(g_target_stop_hook_add_options);
4401 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
4402 ExecutionContext *execution_context) override {
4404 const int short_option = m_getopt_table[option_idx].val;
4406 switch (short_option) {
4408 m_class_name = option_arg;
4409 m_sym_ctx_specified = true;
4413 if (option_arg.getAsInteger(0, m_line_end)) {
4414 error.SetErrorStringWithFormat("invalid end line number: \"%s\"",
4415 option_arg.str().c_str());
4418 m_sym_ctx_specified = true;
4422 if (option_arg.getAsInteger(0, m_line_start)) {
4423 error.SetErrorStringWithFormat("invalid start line number: \"%s\"",
4424 option_arg.str().c_str());
4427 m_sym_ctx_specified = true;
4431 m_no_inlines = true;
4435 m_function_name = option_arg;
4436 m_func_name_type_mask |= eFunctionNameTypeAuto;
4437 m_sym_ctx_specified = true;
4441 m_file_name = option_arg;
4442 m_sym_ctx_specified = true;
4446 m_module_name = option_arg;
4447 m_sym_ctx_specified = true;
4451 if (option_arg.getAsInteger(0, m_thread_id))
4452 error.SetErrorStringWithFormat("invalid thread id string '%s'",
4453 option_arg.str().c_str());
4454 m_thread_specified = true;
4458 m_thread_name = option_arg;
4459 m_thread_specified = true;
4463 m_queue_name = option_arg;
4464 m_thread_specified = true;
4468 if (option_arg.getAsInteger(0, m_thread_index))
4469 error.SetErrorStringWithFormat("invalid thread index string '%s'",
4470 option_arg.str().c_str());
4471 m_thread_specified = true;
4475 m_use_one_liner = true;
4476 m_one_liner = option_arg;
4480 error.SetErrorStringWithFormat("unrecognized option %c.", short_option);
4486 void OptionParsingStarting(ExecutionContext *execution_context) override {
4487 m_class_name.clear();
4488 m_function_name.clear();
4490 m_line_end = UINT_MAX;
4491 m_file_name.clear();
4492 m_module_name.clear();
4493 m_func_name_type_mask = eFunctionNameTypeAuto;
4494 m_thread_id = LLDB_INVALID_THREAD_ID;
4495 m_thread_index = UINT32_MAX;
4496 m_thread_name.clear();
4497 m_queue_name.clear();
4499 m_no_inlines = false;
4500 m_sym_ctx_specified = false;
4501 m_thread_specified = false;
4503 m_use_one_liner = false;
4504 m_one_liner.clear();
4507 std::string m_class_name;
4508 std::string m_function_name;
4509 uint32_t m_line_start;
4510 uint32_t m_line_end;
4511 std::string m_file_name;
4512 std::string m_module_name;
4513 uint32_t m_func_name_type_mask; // A pick from lldb::FunctionNameType.
4514 lldb::tid_t m_thread_id;
4515 uint32_t m_thread_index;
4516 std::string m_thread_name;
4517 std::string m_queue_name;
4518 bool m_sym_ctx_specified;
4520 bool m_thread_specified;
4521 // Instance variables to hold the values for one_liner options.
4522 bool m_use_one_liner;
4523 std::string m_one_liner;
4526 CommandObjectTargetStopHookAdd(CommandInterpreter &interpreter)
4527 : CommandObjectParsed(interpreter, "target stop-hook add",
4528 "Add a hook to be executed when the target stops.",
4529 "target stop-hook add"),
4530 IOHandlerDelegateMultiline("DONE",
4531 IOHandlerDelegate::Completion::LLDBCommand),
4534 ~CommandObjectTargetStopHookAdd() override = default;
4536 Options *GetOptions() override { return &m_options; }
4539 void IOHandlerActivated(IOHandler &io_handler) override {
4540 StreamFileSP output_sp(io_handler.GetOutputStreamFile());
4542 output_sp->PutCString(
4543 "Enter your stop hook command(s). Type 'DONE' to end.\n");
4548 void IOHandlerInputComplete(IOHandler &io_handler,
4549 std::string &line) override {
4550 if (m_stop_hook_sp) {
4552 StreamFileSP error_sp(io_handler.GetErrorStreamFile());
4554 error_sp->Printf("error: stop hook #%" PRIu64
4555 " aborted, no commands.\n",
4556 m_stop_hook_sp->GetID());
4559 Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
4561 target->RemoveStopHookByID(m_stop_hook_sp->GetID());
4563 m_stop_hook_sp->GetCommandPointer()->SplitIntoLines(line);
4564 StreamFileSP output_sp(io_handler.GetOutputStreamFile());
4566 output_sp->Printf("Stop hook #%" PRIu64 " added.\n",
4567 m_stop_hook_sp->GetID());
4571 m_stop_hook_sp.reset();
4573 io_handler.SetIsDone(true);
4576 bool DoExecute(Args &command, CommandReturnObject &result) override {
4577 m_stop_hook_sp.reset();
4579 Target *target = GetSelectedOrDummyTarget();
4581 Target::StopHookSP new_hook_sp = target->CreateStopHook();
4583 // First step, make the specifier.
4584 std::unique_ptr<SymbolContextSpecifier> specifier_ap;
4585 if (m_options.m_sym_ctx_specified) {
4586 specifier_ap.reset(new SymbolContextSpecifier(
4587 m_interpreter.GetDebugger().GetSelectedTarget()));
4589 if (!m_options.m_module_name.empty()) {
4590 specifier_ap->AddSpecification(
4591 m_options.m_module_name.c_str(),
4592 SymbolContextSpecifier::eModuleSpecified);
4595 if (!m_options.m_class_name.empty()) {
4596 specifier_ap->AddSpecification(
4597 m_options.m_class_name.c_str(),
4598 SymbolContextSpecifier::eClassOrNamespaceSpecified);
4601 if (!m_options.m_file_name.empty()) {
4602 specifier_ap->AddSpecification(
4603 m_options.m_file_name.c_str(),
4604 SymbolContextSpecifier::eFileSpecified);
4607 if (m_options.m_line_start != 0) {
4608 specifier_ap->AddLineSpecification(
4609 m_options.m_line_start,
4610 SymbolContextSpecifier::eLineStartSpecified);
4613 if (m_options.m_line_end != UINT_MAX) {
4614 specifier_ap->AddLineSpecification(
4615 m_options.m_line_end, SymbolContextSpecifier::eLineEndSpecified);
4618 if (!m_options.m_function_name.empty()) {
4619 specifier_ap->AddSpecification(
4620 m_options.m_function_name.c_str(),
4621 SymbolContextSpecifier::eFunctionSpecified);
4626 new_hook_sp->SetSpecifier(specifier_ap.release());
4628 // Next see if any of the thread options have been entered:
4630 if (m_options.m_thread_specified) {
4631 ThreadSpec *thread_spec = new ThreadSpec();
4633 if (m_options.m_thread_id != LLDB_INVALID_THREAD_ID) {
4634 thread_spec->SetTID(m_options.m_thread_id);
4637 if (m_options.m_thread_index != UINT32_MAX)
4638 thread_spec->SetIndex(m_options.m_thread_index);
4640 if (!m_options.m_thread_name.empty())
4641 thread_spec->SetName(m_options.m_thread_name.c_str());
4643 if (!m_options.m_queue_name.empty())
4644 thread_spec->SetQueueName(m_options.m_queue_name.c_str());
4646 new_hook_sp->SetThreadSpecifier(thread_spec);
4648 if (m_options.m_use_one_liner) {
4650 new_hook_sp->GetCommandPointer()->AppendString(
4651 m_options.m_one_liner.c_str());
4652 result.AppendMessageWithFormat("Stop hook #%" PRIu64 " added.\n",
4653 new_hook_sp->GetID());
4655 m_stop_hook_sp = new_hook_sp;
4656 m_interpreter.GetLLDBCommandsFromIOHandler(
4658 *this, // IOHandlerDelegate
4659 true, // Run IOHandler in async mode
4660 nullptr); // Baton for the "io_handler" that will be passed back
4661 // into our IOHandlerDelegate functions
4663 result.SetStatus(eReturnStatusSuccessFinishNoResult);
4665 result.AppendError("invalid target\n");
4666 result.SetStatus(eReturnStatusFailed);
4669 return result.Succeeded();
4673 CommandOptions m_options;
4674 Target::StopHookSP m_stop_hook_sp;
4677 #pragma mark CommandObjectTargetStopHookDelete
4679 //-------------------------------------------------------------------------
4680 // CommandObjectTargetStopHookDelete
4681 //-------------------------------------------------------------------------
4683 class CommandObjectTargetStopHookDelete : public CommandObjectParsed {
4685 CommandObjectTargetStopHookDelete(CommandInterpreter &interpreter)
4686 : CommandObjectParsed(interpreter, "target stop-hook delete",
4687 "Delete a stop-hook.",
4688 "target stop-hook delete [<idx>]") {}
4690 ~CommandObjectTargetStopHookDelete() override = default;
4693 bool DoExecute(Args &command, CommandReturnObject &result) override {
4694 Target *target = GetSelectedOrDummyTarget();
4696 // FIXME: see if we can use the breakpoint id style parser?
4697 size_t num_args = command.GetArgumentCount();
4698 if (num_args == 0) {
4699 if (!m_interpreter.Confirm("Delete all stop hooks?", true)) {
4700 result.SetStatus(eReturnStatusFailed);
4703 target->RemoveAllStopHooks();
4707 for (size_t i = 0; i < num_args; i++) {
4708 lldb::user_id_t user_id = StringConvert::ToUInt32(
4709 command.GetArgumentAtIndex(i), 0, 0, &success);
4711 result.AppendErrorWithFormat("invalid stop hook id: \"%s\".\n",
4712 command.GetArgumentAtIndex(i));
4713 result.SetStatus(eReturnStatusFailed);
4716 success = target->RemoveStopHookByID(user_id);
4718 result.AppendErrorWithFormat("unknown stop hook id: \"%s\".\n",
4719 command.GetArgumentAtIndex(i));
4720 result.SetStatus(eReturnStatusFailed);
4725 result.SetStatus(eReturnStatusSuccessFinishNoResult);
4727 result.AppendError("invalid target\n");
4728 result.SetStatus(eReturnStatusFailed);
4731 return result.Succeeded();
4735 #pragma mark CommandObjectTargetStopHookEnableDisable
4737 //-------------------------------------------------------------------------
4738 // CommandObjectTargetStopHookEnableDisable
4739 //-------------------------------------------------------------------------
4741 class CommandObjectTargetStopHookEnableDisable : public CommandObjectParsed {
4743 CommandObjectTargetStopHookEnableDisable(CommandInterpreter &interpreter,
4744 bool enable, const char *name,
4745 const char *help, const char *syntax)
4746 : CommandObjectParsed(interpreter, name, help, syntax), m_enable(enable) {
4749 ~CommandObjectTargetStopHookEnableDisable() override = default;
4752 bool DoExecute(Args &command, CommandReturnObject &result) override {
4753 Target *target = GetSelectedOrDummyTarget();
4755 // FIXME: see if we can use the breakpoint id style parser?
4756 size_t num_args = command.GetArgumentCount();
4759 if (num_args == 0) {
4760 target->SetAllStopHooksActiveState(m_enable);
4762 for (size_t i = 0; i < num_args; i++) {
4763 lldb::user_id_t user_id = StringConvert::ToUInt32(
4764 command.GetArgumentAtIndex(i), 0, 0, &success);
4766 result.AppendErrorWithFormat("invalid stop hook id: \"%s\".\n",
4767 command.GetArgumentAtIndex(i));
4768 result.SetStatus(eReturnStatusFailed);
4771 success = target->SetStopHookActiveStateByID(user_id, m_enable);
4773 result.AppendErrorWithFormat("unknown stop hook id: \"%s\".\n",
4774 command.GetArgumentAtIndex(i));
4775 result.SetStatus(eReturnStatusFailed);
4780 result.SetStatus(eReturnStatusSuccessFinishNoResult);
4782 result.AppendError("invalid target\n");
4783 result.SetStatus(eReturnStatusFailed);
4785 return result.Succeeded();
4792 #pragma mark CommandObjectTargetStopHookList
4794 //-------------------------------------------------------------------------
4795 // CommandObjectTargetStopHookList
4796 //-------------------------------------------------------------------------
4798 class CommandObjectTargetStopHookList : public CommandObjectParsed {
4800 CommandObjectTargetStopHookList(CommandInterpreter &interpreter)
4801 : CommandObjectParsed(interpreter, "target stop-hook list",
4802 "List all stop-hooks.",
4803 "target stop-hook list [<type>]") {}
4805 ~CommandObjectTargetStopHookList() override = default;
4808 bool DoExecute(Args &command, CommandReturnObject &result) override {
4809 Target *target = GetSelectedOrDummyTarget();
4811 result.AppendError("invalid target\n");
4812 result.SetStatus(eReturnStatusFailed);
4813 return result.Succeeded();
4816 size_t num_hooks = target->GetNumStopHooks();
4817 if (num_hooks == 0) {
4818 result.GetOutputStream().PutCString("No stop hooks.\n");
4820 for (size_t i = 0; i < num_hooks; i++) {
4821 Target::StopHookSP this_hook = target->GetStopHookAtIndex(i);
4823 result.GetOutputStream().PutCString("\n");
4824 this_hook->GetDescription(&(result.GetOutputStream()),
4825 eDescriptionLevelFull);
4828 result.SetStatus(eReturnStatusSuccessFinishResult);
4829 return result.Succeeded();
4833 #pragma mark CommandObjectMultiwordTargetStopHooks
4835 //-------------------------------------------------------------------------
4836 // CommandObjectMultiwordTargetStopHooks
4837 //-------------------------------------------------------------------------
4839 class CommandObjectMultiwordTargetStopHooks : public CommandObjectMultiword {
4841 CommandObjectMultiwordTargetStopHooks(CommandInterpreter &interpreter)
4842 : CommandObjectMultiword(
4843 interpreter, "target stop-hook",
4844 "Commands for operating on debugger target stop-hooks.",
4845 "target stop-hook <subcommand> [<subcommand-options>]") {
4846 LoadSubCommand("add", CommandObjectSP(
4847 new CommandObjectTargetStopHookAdd(interpreter)));
4850 CommandObjectSP(new CommandObjectTargetStopHookDelete(interpreter)));
4851 LoadSubCommand("disable",
4852 CommandObjectSP(new CommandObjectTargetStopHookEnableDisable(
4853 interpreter, false, "target stop-hook disable [<id>]",
4854 "Disable a stop-hook.", "target stop-hook disable")));
4855 LoadSubCommand("enable",
4856 CommandObjectSP(new CommandObjectTargetStopHookEnableDisable(
4857 interpreter, true, "target stop-hook enable [<id>]",
4858 "Enable a stop-hook.", "target stop-hook enable")));
4859 LoadSubCommand("list", CommandObjectSP(new CommandObjectTargetStopHookList(
4863 ~CommandObjectMultiwordTargetStopHooks() override = default;
4866 #pragma mark CommandObjectMultiwordTarget
4868 //-------------------------------------------------------------------------
4869 // CommandObjectMultiwordTarget
4870 //-------------------------------------------------------------------------
4872 CommandObjectMultiwordTarget::CommandObjectMultiwordTarget(
4873 CommandInterpreter &interpreter)
4874 : CommandObjectMultiword(interpreter, "target",
4875 "Commands for operating on debugger targets.",
4876 "target <subcommand> [<subcommand-options>]") {
4877 LoadSubCommand("create",
4878 CommandObjectSP(new CommandObjectTargetCreate(interpreter)));
4879 LoadSubCommand("delete",
4880 CommandObjectSP(new CommandObjectTargetDelete(interpreter)));
4881 LoadSubCommand("list",
4882 CommandObjectSP(new CommandObjectTargetList(interpreter)));
4883 LoadSubCommand("select",
4884 CommandObjectSP(new CommandObjectTargetSelect(interpreter)));
4887 CommandObjectSP(new CommandObjectMultiwordTargetStopHooks(interpreter)));
4888 LoadSubCommand("modules",
4889 CommandObjectSP(new CommandObjectTargetModules(interpreter)));
4890 LoadSubCommand("symbols",
4891 CommandObjectSP(new CommandObjectTargetSymbols(interpreter)));
4892 LoadSubCommand("variable",
4893 CommandObjectSP(new CommandObjectTargetVariable(interpreter)));
4896 CommandObjectMultiwordTarget::~CommandObjectMultiwordTarget() = default;