1 //===-- CommandObjectTarget.cpp ---------------------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "CommandObjectTarget.h"
10 
11 #include "lldb/Core/Debugger.h"
12 #include "lldb/Core/IOHandler.h"
13 #include "lldb/Core/Module.h"
14 #include "lldb/Core/ModuleSpec.h"
15 #include "lldb/Core/Section.h"
16 #include "lldb/Core/ValueObjectVariable.h"
17 #include "lldb/DataFormatters/ValueObjectPrinter.h"
18 #include "lldb/Host/OptionParser.h"
19 #include "lldb/Host/StringConvert.h"
20 #include "lldb/Interpreter/CommandInterpreter.h"
21 #include "lldb/Interpreter/CommandReturnObject.h"
22 #include "lldb/Interpreter/OptionArgParser.h"
23 #include "lldb/Interpreter/OptionGroupArchitecture.h"
24 #include "lldb/Interpreter/OptionGroupBoolean.h"
25 #include "lldb/Interpreter/OptionGroupFile.h"
26 #include "lldb/Interpreter/OptionGroupFormat.h"
27 #include "lldb/Interpreter/OptionGroupPlatform.h"
28 #include "lldb/Interpreter/OptionGroupString.h"
29 #include "lldb/Interpreter/OptionGroupUInt64.h"
30 #include "lldb/Interpreter/OptionGroupUUID.h"
31 #include "lldb/Interpreter/OptionGroupValueObjectDisplay.h"
32 #include "lldb/Interpreter/OptionGroupVariable.h"
33 #include "lldb/Interpreter/Options.h"
34 #include "lldb/Symbol/CompileUnit.h"
35 #include "lldb/Symbol/FuncUnwinders.h"
36 #include "lldb/Symbol/LineTable.h"
37 #include "lldb/Symbol/LocateSymbolFile.h"
38 #include "lldb/Symbol/ObjectFile.h"
39 #include "lldb/Symbol/SymbolFile.h"
40 #include "lldb/Symbol/UnwindPlan.h"
41 #include "lldb/Symbol/VariableList.h"
42 #include "lldb/Target/ABI.h"
43 #include "lldb/Target/Process.h"
44 #include "lldb/Target/RegisterContext.h"
45 #include "lldb/Target/SectionLoadList.h"
46 #include "lldb/Target/StackFrame.h"
47 #include "lldb/Target/Thread.h"
48 #include "lldb/Target/ThreadSpec.h"
49 #include "lldb/Utility/Args.h"
50 #include "lldb/Utility/State.h"
51 #include "lldb/Utility/Timer.h"
52 
53 #include "llvm/Support/FileSystem.h"
54 #include "llvm/Support/FormatAdapters.h"
55 
56 #include <cerrno>
57 
58 using namespace lldb;
59 using namespace lldb_private;
60 
61 static void DumpTargetInfo(uint32_t target_idx, Target *target,
62                            const char *prefix_cstr,
63                            bool show_stopped_process_status, Stream &strm) {
64   const ArchSpec &target_arch = target->GetArchitecture();
65 
66   Module *exe_module = target->GetExecutableModulePointer();
67   char exe_path[PATH_MAX];
68   bool exe_valid = false;
69   if (exe_module)
70     exe_valid = exe_module->GetFileSpec().GetPath(exe_path, sizeof(exe_path));
71 
72   if (!exe_valid)
73     ::strcpy(exe_path, "<none>");
74 
75   strm.Printf("%starget #%u: %s", prefix_cstr ? prefix_cstr : "", target_idx,
76               exe_path);
77 
78   uint32_t properties = 0;
79   if (target_arch.IsValid()) {
80     strm.Printf("%sarch=", properties++ > 0 ? ", " : " ( ");
81     target_arch.DumpTriple(strm);
82     properties++;
83   }
84   PlatformSP platform_sp(target->GetPlatform());
85   if (platform_sp)
86     strm.Printf("%splatform=%s", properties++ > 0 ? ", " : " ( ",
87                 platform_sp->GetName().GetCString());
88 
89   ProcessSP process_sp(target->GetProcessSP());
90   bool show_process_status = false;
91   if (process_sp) {
92     lldb::pid_t pid = process_sp->GetID();
93     StateType state = process_sp->GetState();
94     if (show_stopped_process_status)
95       show_process_status = StateIsStoppedState(state, true);
96     const char *state_cstr = StateAsCString(state);
97     if (pid != LLDB_INVALID_PROCESS_ID)
98       strm.Printf("%spid=%" PRIu64, properties++ > 0 ? ", " : " ( ", pid);
99     strm.Printf("%sstate=%s", properties++ > 0 ? ", " : " ( ", state_cstr);
100   }
101   if (properties > 0)
102     strm.PutCString(" )\n");
103   else
104     strm.EOL();
105   if (show_process_status) {
106     const bool only_threads_with_stop_reason = true;
107     const uint32_t start_frame = 0;
108     const uint32_t num_frames = 1;
109     const uint32_t num_frames_with_source = 1;
110     const bool     stop_format = false;
111     process_sp->GetStatus(strm);
112     process_sp->GetThreadStatus(strm, only_threads_with_stop_reason,
113                                 start_frame, num_frames,
114                                 num_frames_with_source, stop_format);
115   }
116 }
117 
118 static uint32_t DumpTargetList(TargetList &target_list,
119                                bool show_stopped_process_status, Stream &strm) {
120   const uint32_t num_targets = target_list.GetNumTargets();
121   if (num_targets) {
122     TargetSP selected_target_sp(target_list.GetSelectedTarget());
123     strm.PutCString("Current targets:\n");
124     for (uint32_t i = 0; i < num_targets; ++i) {
125       TargetSP target_sp(target_list.GetTargetAtIndex(i));
126       if (target_sp) {
127         bool is_selected = target_sp.get() == selected_target_sp.get();
128         DumpTargetInfo(i, target_sp.get(), is_selected ? "* " : "  ",
129                        show_stopped_process_status, strm);
130       }
131     }
132   }
133   return num_targets;
134 }
135 
136 // Note that the negation in the argument name causes a slightly confusing
137 // mapping of the enum values.
138 static constexpr OptionEnumValueElement g_dependents_enumaration[] = {
139     {
140         eLoadDependentsDefault,
141         "default",
142         "Only load dependents when the target is an executable.",
143     },
144     {
145         eLoadDependentsNo,
146         "true",
147         "Don't load dependents, even if the target is an executable.",
148     },
149     {
150         eLoadDependentsYes,
151         "false",
152         "Load dependents, even if the target is not an executable.",
153     },
154 };
155 
156 #define LLDB_OPTIONS_target_dependents
157 #include "CommandOptions.inc"
158 
159 class OptionGroupDependents : public OptionGroup {
160 public:
161   OptionGroupDependents() {}
162 
163   ~OptionGroupDependents() override {}
164 
165   llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
166     return llvm::makeArrayRef(g_target_dependents_options);
167   }
168 
169   Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value,
170                         ExecutionContext *execution_context) override {
171     Status error;
172 
173     // For compatibility no value means don't load dependents.
174     if (option_value.empty()) {
175       m_load_dependent_files = eLoadDependentsNo;
176       return error;
177     }
178 
179     const char short_option =
180         g_target_dependents_options[option_idx].short_option;
181     if (short_option == 'd') {
182       LoadDependentFiles tmp_load_dependents;
183       tmp_load_dependents = (LoadDependentFiles)OptionArgParser::ToOptionEnum(
184           option_value, g_target_dependents_options[option_idx].enum_values, 0,
185           error);
186       if (error.Success())
187         m_load_dependent_files = tmp_load_dependents;
188     } else {
189       error.SetErrorStringWithFormat("unrecognized short option '%c'",
190                                      short_option);
191     }
192 
193     return error;
194   }
195 
196   Status SetOptionValue(uint32_t, const char *, ExecutionContext *) = delete;
197 
198   void OptionParsingStarting(ExecutionContext *execution_context) override {
199     m_load_dependent_files = eLoadDependentsDefault;
200   }
201 
202   LoadDependentFiles m_load_dependent_files;
203 
204 private:
205   DISALLOW_COPY_AND_ASSIGN(OptionGroupDependents);
206 };
207 
208 #pragma mark CommandObjectTargetCreate
209 
210 // "target create"
211 
212 class CommandObjectTargetCreate : public CommandObjectParsed {
213 public:
214   CommandObjectTargetCreate(CommandInterpreter &interpreter)
215       : CommandObjectParsed(
216             interpreter, "target create",
217             "Create a target using the argument as the main executable.",
218             nullptr),
219         m_option_group(), m_arch_option(),
220         m_core_file(LLDB_OPT_SET_1, false, "core", 'c', 0, eArgTypeFilename,
221                     "Fullpath to a core file to use for this target."),
222         m_platform_path(LLDB_OPT_SET_1, false, "platform-path", 'P', 0,
223                         eArgTypePath,
224                         "Path to the remote file to use for this target."),
225         m_symbol_file(LLDB_OPT_SET_1, false, "symfile", 's', 0,
226                       eArgTypeFilename,
227                       "Fullpath to a stand alone debug "
228                       "symbols file for when debug symbols "
229                       "are not in the executable."),
230         m_remote_file(
231             LLDB_OPT_SET_1, false, "remote-file", 'r', 0, eArgTypeFilename,
232             "Fullpath to the file on the remote host if debugging remotely."),
233         m_add_dependents() {
234     CommandArgumentEntry arg;
235     CommandArgumentData file_arg;
236 
237     // Define the first (and only) variant of this arg.
238     file_arg.arg_type = eArgTypeFilename;
239     file_arg.arg_repetition = eArgRepeatPlain;
240 
241     // There is only one variant this argument could be; put it into the
242     // argument entry.
243     arg.push_back(file_arg);
244 
245     // Push the data for the first argument into the m_arguments vector.
246     m_arguments.push_back(arg);
247 
248     m_option_group.Append(&m_arch_option, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
249     m_option_group.Append(&m_core_file, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
250     m_option_group.Append(&m_platform_path, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
251     m_option_group.Append(&m_symbol_file, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
252     m_option_group.Append(&m_remote_file, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
253     m_option_group.Append(&m_add_dependents, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
254     m_option_group.Finalize();
255   }
256 
257   ~CommandObjectTargetCreate() override = default;
258 
259   Options *GetOptions() override { return &m_option_group; }
260 
261   void
262   HandleArgumentCompletion(CompletionRequest &request,
263                            OptionElementVector &opt_element_vector) override {
264     CommandCompletions::InvokeCommonCompletionCallbacks(
265         GetCommandInterpreter(), CommandCompletions::eDiskFileCompletion,
266         request, nullptr);
267   }
268 
269 protected:
270   bool DoExecute(Args &command, CommandReturnObject &result) override {
271     const size_t argc = command.GetArgumentCount();
272     FileSpec core_file(m_core_file.GetOptionValue().GetCurrentValue());
273     FileSpec remote_file(m_remote_file.GetOptionValue().GetCurrentValue());
274 
275     if (core_file) {
276       if (!FileSystem::Instance().Exists(core_file)) {
277         result.AppendErrorWithFormat("core file '%s' doesn't exist",
278                                      core_file.GetPath().c_str());
279         result.SetStatus(eReturnStatusFailed);
280         return false;
281       }
282       if (!FileSystem::Instance().Readable(core_file)) {
283         result.AppendErrorWithFormat("core file '%s' is not readable",
284                                      core_file.GetPath().c_str());
285         result.SetStatus(eReturnStatusFailed);
286         return false;
287       }
288     }
289 
290     if (argc == 1 || core_file || remote_file) {
291       FileSpec symfile(m_symbol_file.GetOptionValue().GetCurrentValue());
292       if (symfile) {
293         if (FileSystem::Instance().Exists(symfile)) {
294           if (!FileSystem::Instance().Readable(symfile)) {
295             result.AppendErrorWithFormat("symbol file '%s' is not readable",
296                                          symfile.GetPath().c_str());
297             result.SetStatus(eReturnStatusFailed);
298             return false;
299           }
300         } else {
301           char symfile_path[PATH_MAX];
302           symfile.GetPath(symfile_path, sizeof(symfile_path));
303           result.AppendErrorWithFormat("invalid symbol file path '%s'",
304                                        symfile_path);
305           result.SetStatus(eReturnStatusFailed);
306           return false;
307         }
308       }
309 
310       const char *file_path = command.GetArgumentAtIndex(0);
311       static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
312       Timer scoped_timer(func_cat, "(lldb) target create '%s'", file_path);
313       FileSpec file_spec;
314 
315       if (file_path) {
316         file_spec.SetFile(file_path, FileSpec::Style::native);
317         FileSystem::Instance().Resolve(file_spec);
318       }
319 
320       bool must_set_platform_path = false;
321 
322       Debugger &debugger = GetDebugger();
323 
324       TargetSP target_sp;
325       llvm::StringRef arch_cstr = m_arch_option.GetArchitectureName();
326       Status error(debugger.GetTargetList().CreateTarget(
327           debugger, file_path, arch_cstr,
328           m_add_dependents.m_load_dependent_files, nullptr, target_sp));
329 
330       if (target_sp) {
331         // Only get the platform after we create the target because we might
332         // have switched platforms depending on what the arguments were to
333         // CreateTarget() we can't rely on the selected platform.
334 
335         PlatformSP platform_sp = target_sp->GetPlatform();
336 
337         if (remote_file) {
338           if (platform_sp) {
339             // I have a remote file.. two possible cases
340             if (file_spec && FileSystem::Instance().Exists(file_spec)) {
341               // if the remote file does not exist, push it there
342               if (!platform_sp->GetFileExists(remote_file)) {
343                 Status err = platform_sp->PutFile(file_spec, remote_file);
344                 if (err.Fail()) {
345                   result.AppendError(err.AsCString());
346                   result.SetStatus(eReturnStatusFailed);
347                   return false;
348                 }
349               }
350             } else {
351               // there is no local file and we need one
352               // in order to make the remote ---> local transfer we need a
353               // platform
354               // TODO: if the user has passed in a --platform argument, use it
355               // to fetch the right platform
356               if (!platform_sp) {
357                 result.AppendError(
358                     "unable to perform remote debugging without a platform");
359                 result.SetStatus(eReturnStatusFailed);
360                 return false;
361               }
362               if (file_path) {
363                 // copy the remote file to the local file
364                 Status err = platform_sp->GetFile(remote_file, file_spec);
365                 if (err.Fail()) {
366                   result.AppendError(err.AsCString());
367                   result.SetStatus(eReturnStatusFailed);
368                   return false;
369                 }
370               } else {
371                 // make up a local file
372                 result.AppendError("remote --> local transfer without local "
373                                    "path is not implemented yet");
374                 result.SetStatus(eReturnStatusFailed);
375                 return false;
376               }
377             }
378           } else {
379             result.AppendError("no platform found for target");
380             result.SetStatus(eReturnStatusFailed);
381             return false;
382           }
383         }
384 
385         if (symfile || remote_file) {
386           ModuleSP module_sp(target_sp->GetExecutableModule());
387           if (module_sp) {
388             if (symfile)
389               module_sp->SetSymbolFileFileSpec(symfile);
390             if (remote_file) {
391               std::string remote_path = remote_file.GetPath();
392               target_sp->SetArg0(remote_path.c_str());
393               module_sp->SetPlatformFileSpec(remote_file);
394             }
395           }
396         }
397 
398         debugger.GetTargetList().SetSelectedTarget(target_sp.get());
399         if (must_set_platform_path) {
400           ModuleSpec main_module_spec(file_spec);
401           ModuleSP module_sp = target_sp->GetOrCreateModule(main_module_spec,
402                                                           true /* notify */);
403           if (module_sp)
404             module_sp->SetPlatformFileSpec(remote_file);
405         }
406         if (core_file) {
407           char core_path[PATH_MAX];
408           core_file.GetPath(core_path, sizeof(core_path));
409           if (FileSystem::Instance().Exists(core_file)) {
410             if (!FileSystem::Instance().Readable(core_file)) {
411               result.AppendMessageWithFormat(
412                   "Core file '%s' is not readable.\n", core_path);
413               result.SetStatus(eReturnStatusFailed);
414               return false;
415             }
416             FileSpec core_file_dir;
417             core_file_dir.GetDirectory() = core_file.GetDirectory();
418             target_sp->AppendExecutableSearchPaths(core_file_dir);
419 
420             ProcessSP process_sp(target_sp->CreateProcess(
421                 GetDebugger().GetListener(), llvm::StringRef(), &core_file));
422 
423             if (process_sp) {
424               // Seems weird that we Launch a core file, but that is what we
425               // do!
426               error = process_sp->LoadCore();
427 
428               if (error.Fail()) {
429                 result.AppendError(
430                     error.AsCString("can't find plug-in for core file"));
431                 result.SetStatus(eReturnStatusFailed);
432                 return false;
433               } else {
434                 result.AppendMessageWithFormat(
435                     "Core file '%s' (%s) was loaded.\n", core_path,
436                     target_sp->GetArchitecture().GetArchitectureName());
437                 result.SetStatus(eReturnStatusSuccessFinishNoResult);
438               }
439             } else {
440               result.AppendErrorWithFormat(
441                   "Unable to find process plug-in for core file '%s'\n",
442                   core_path);
443               result.SetStatus(eReturnStatusFailed);
444             }
445           } else {
446             result.AppendErrorWithFormat("Core file '%s' does not exist\n",
447                                          core_path);
448             result.SetStatus(eReturnStatusFailed);
449           }
450         } else {
451           result.AppendMessageWithFormat(
452               "Current executable set to '%s' (%s).\n",
453               file_spec.GetPath().c_str(),
454               target_sp->GetArchitecture().GetArchitectureName());
455           result.SetStatus(eReturnStatusSuccessFinishNoResult);
456         }
457       } else {
458         result.AppendError(error.AsCString());
459         result.SetStatus(eReturnStatusFailed);
460       }
461     } else {
462       result.AppendErrorWithFormat("'%s' takes exactly one executable path "
463                                    "argument, or use the --core option.\n",
464                                    m_cmd_name.c_str());
465       result.SetStatus(eReturnStatusFailed);
466     }
467     return result.Succeeded();
468   }
469 
470 private:
471   OptionGroupOptions m_option_group;
472   OptionGroupArchitecture m_arch_option;
473   OptionGroupFile m_core_file;
474   OptionGroupFile m_platform_path;
475   OptionGroupFile m_symbol_file;
476   OptionGroupFile m_remote_file;
477   OptionGroupDependents m_add_dependents;
478 };
479 
480 #pragma mark CommandObjectTargetList
481 
482 // "target list"
483 
484 class CommandObjectTargetList : public CommandObjectParsed {
485 public:
486   CommandObjectTargetList(CommandInterpreter &interpreter)
487       : CommandObjectParsed(
488             interpreter, "target list",
489             "List all current targets in the current debug session.", nullptr) {
490   }
491 
492   ~CommandObjectTargetList() override = default;
493 
494 protected:
495   bool DoExecute(Args &args, CommandReturnObject &result) override {
496     if (args.GetArgumentCount() == 0) {
497       Stream &strm = result.GetOutputStream();
498 
499       bool show_stopped_process_status = false;
500       if (DumpTargetList(GetDebugger().GetTargetList(),
501                          show_stopped_process_status, strm) == 0) {
502         strm.PutCString("No targets.\n");
503       }
504       result.SetStatus(eReturnStatusSuccessFinishResult);
505     } else {
506       result.AppendError("the 'target list' command takes no arguments\n");
507       result.SetStatus(eReturnStatusFailed);
508     }
509     return result.Succeeded();
510   }
511 };
512 
513 #pragma mark CommandObjectTargetSelect
514 
515 // "target select"
516 
517 class CommandObjectTargetSelect : public CommandObjectParsed {
518 public:
519   CommandObjectTargetSelect(CommandInterpreter &interpreter)
520       : CommandObjectParsed(
521             interpreter, "target select",
522             "Select a target as the current target by target index.", nullptr) {
523   }
524 
525   ~CommandObjectTargetSelect() override = default;
526 
527 protected:
528   bool DoExecute(Args &args, CommandReturnObject &result) override {
529     if (args.GetArgumentCount() == 1) {
530       bool success = false;
531       const char *target_idx_arg = args.GetArgumentAtIndex(0);
532       uint32_t target_idx =
533           StringConvert::ToUInt32(target_idx_arg, UINT32_MAX, 0, &success);
534       if (success) {
535         TargetList &target_list = GetDebugger().GetTargetList();
536         const uint32_t num_targets = target_list.GetNumTargets();
537         if (target_idx < num_targets) {
538           TargetSP target_sp(target_list.GetTargetAtIndex(target_idx));
539           if (target_sp) {
540             Stream &strm = result.GetOutputStream();
541             target_list.SetSelectedTarget(target_sp.get());
542             bool show_stopped_process_status = false;
543             DumpTargetList(target_list, show_stopped_process_status, strm);
544             result.SetStatus(eReturnStatusSuccessFinishResult);
545           } else {
546             result.AppendErrorWithFormat("target #%u is NULL in target list\n",
547                                          target_idx);
548             result.SetStatus(eReturnStatusFailed);
549           }
550         } else {
551           if (num_targets > 0) {
552             result.AppendErrorWithFormat(
553                 "index %u is out of range, valid target indexes are 0 - %u\n",
554                 target_idx, num_targets - 1);
555           } else {
556             result.AppendErrorWithFormat(
557                 "index %u is out of range since there are no active targets\n",
558                 target_idx);
559           }
560           result.SetStatus(eReturnStatusFailed);
561         }
562       } else {
563         result.AppendErrorWithFormat("invalid index string value '%s'\n",
564                                      target_idx_arg);
565         result.SetStatus(eReturnStatusFailed);
566       }
567     } else {
568       result.AppendError(
569           "'target select' takes a single argument: a target index\n");
570       result.SetStatus(eReturnStatusFailed);
571     }
572     return result.Succeeded();
573   }
574 };
575 
576 #pragma mark CommandObjectTargetSelect
577 
578 // "target delete"
579 
580 class CommandObjectTargetDelete : public CommandObjectParsed {
581 public:
582   CommandObjectTargetDelete(CommandInterpreter &interpreter)
583       : CommandObjectParsed(interpreter, "target delete",
584                             "Delete one or more targets by target index.",
585                             nullptr),
586         m_option_group(), m_all_option(LLDB_OPT_SET_1, false, "all", 'a',
587                                        "Delete all targets.", false, true),
588         m_cleanup_option(
589             LLDB_OPT_SET_1, false, "clean", 'c',
590             "Perform extra cleanup to minimize memory consumption after "
591             "deleting the target.  "
592             "By default, LLDB will keep in memory any modules previously "
593             "loaded by the target as well "
594             "as all of its debug info.  Specifying --clean will unload all of "
595             "these shared modules and "
596             "cause them to be reparsed again the next time the target is run",
597             false, true) {
598     m_option_group.Append(&m_all_option, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
599     m_option_group.Append(&m_cleanup_option, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
600     m_option_group.Finalize();
601   }
602 
603   ~CommandObjectTargetDelete() override = default;
604 
605   Options *GetOptions() override { return &m_option_group; }
606 
607 protected:
608   bool DoExecute(Args &args, CommandReturnObject &result) override {
609     const size_t argc = args.GetArgumentCount();
610     std::vector<TargetSP> delete_target_list;
611     TargetList &target_list = GetDebugger().GetTargetList();
612     TargetSP target_sp;
613 
614     if (m_all_option.GetOptionValue()) {
615       for (int i = 0; i < target_list.GetNumTargets(); ++i)
616         delete_target_list.push_back(target_list.GetTargetAtIndex(i));
617     } else if (argc > 0) {
618       const uint32_t num_targets = target_list.GetNumTargets();
619       // Bail out if don't have any targets.
620       if (num_targets == 0) {
621         result.AppendError("no targets to delete");
622         result.SetStatus(eReturnStatusFailed);
623         return false;
624       }
625 
626       for (auto &entry : args.entries()) {
627         uint32_t target_idx;
628         if (entry.ref().getAsInteger(0, target_idx)) {
629           result.AppendErrorWithFormat("invalid target index '%s'\n",
630                                        entry.c_str());
631           result.SetStatus(eReturnStatusFailed);
632           return false;
633         }
634         if (target_idx < num_targets) {
635           target_sp = target_list.GetTargetAtIndex(target_idx);
636           if (target_sp) {
637             delete_target_list.push_back(target_sp);
638             continue;
639           }
640         }
641         if (num_targets > 1)
642           result.AppendErrorWithFormat("target index %u is out of range, valid "
643                                        "target indexes are 0 - %u\n",
644                                        target_idx, num_targets - 1);
645         else
646           result.AppendErrorWithFormat(
647               "target index %u is out of range, the only valid index is 0\n",
648               target_idx);
649 
650         result.SetStatus(eReturnStatusFailed);
651         return false;
652       }
653     } else {
654       target_sp = target_list.GetSelectedTarget();
655       if (!target_sp) {
656         result.AppendErrorWithFormat("no target is currently selected\n");
657         result.SetStatus(eReturnStatusFailed);
658         return false;
659       }
660       delete_target_list.push_back(target_sp);
661     }
662 
663     const size_t num_targets_to_delete = delete_target_list.size();
664     for (size_t idx = 0; idx < num_targets_to_delete; ++idx) {
665       target_sp = delete_target_list[idx];
666       target_list.DeleteTarget(target_sp);
667       target_sp->Destroy();
668     }
669     // If "--clean" was specified, prune any orphaned shared modules from the
670     // global shared module list
671     if (m_cleanup_option.GetOptionValue()) {
672       const bool mandatory = true;
673       ModuleList::RemoveOrphanSharedModules(mandatory);
674     }
675     result.GetOutputStream().Printf("%u targets deleted.\n",
676                                     (uint32_t)num_targets_to_delete);
677     result.SetStatus(eReturnStatusSuccessFinishResult);
678 
679     return true;
680   }
681 
682   OptionGroupOptions m_option_group;
683   OptionGroupBoolean m_all_option;
684   OptionGroupBoolean m_cleanup_option;
685 };
686 
687 #pragma mark CommandObjectTargetVariable
688 
689 // "target variable"
690 
691 class CommandObjectTargetVariable : public CommandObjectParsed {
692   static const uint32_t SHORT_OPTION_FILE = 0x66696c65; // 'file'
693   static const uint32_t SHORT_OPTION_SHLB = 0x73686c62; // 'shlb'
694 
695 public:
696   CommandObjectTargetVariable(CommandInterpreter &interpreter)
697       : CommandObjectParsed(interpreter, "target variable",
698                             "Read global variables for the current target, "
699                             "before or while running a process.",
700                             nullptr, eCommandRequiresTarget),
701         m_option_group(),
702         m_option_variable(false), // Don't include frame options
703         m_option_format(eFormatDefault),
704         m_option_compile_units(LLDB_OPT_SET_1, false, "file", SHORT_OPTION_FILE,
705                                0, eArgTypeFilename,
706                                "A basename or fullpath to a file that contains "
707                                "global variables. This option can be "
708                                "specified multiple times."),
709         m_option_shared_libraries(
710             LLDB_OPT_SET_1, false, "shlib", SHORT_OPTION_SHLB, 0,
711             eArgTypeFilename,
712             "A basename or fullpath to a shared library to use in the search "
713             "for global "
714             "variables. This option can be specified multiple times."),
715         m_varobj_options() {
716     CommandArgumentEntry arg;
717     CommandArgumentData var_name_arg;
718 
719     // Define the first (and only) variant of this arg.
720     var_name_arg.arg_type = eArgTypeVarName;
721     var_name_arg.arg_repetition = eArgRepeatPlus;
722 
723     // There is only one variant this argument could be; put it into the
724     // argument entry.
725     arg.push_back(var_name_arg);
726 
727     // Push the data for the first argument into the m_arguments vector.
728     m_arguments.push_back(arg);
729 
730     m_option_group.Append(&m_varobj_options, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
731     m_option_group.Append(&m_option_variable, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
732     m_option_group.Append(&m_option_format,
733                           OptionGroupFormat::OPTION_GROUP_FORMAT |
734                               OptionGroupFormat::OPTION_GROUP_GDB_FMT,
735                           LLDB_OPT_SET_1);
736     m_option_group.Append(&m_option_compile_units, LLDB_OPT_SET_ALL,
737                           LLDB_OPT_SET_1);
738     m_option_group.Append(&m_option_shared_libraries, LLDB_OPT_SET_ALL,
739                           LLDB_OPT_SET_1);
740     m_option_group.Finalize();
741   }
742 
743   ~CommandObjectTargetVariable() override = default;
744 
745   void DumpValueObject(Stream &s, VariableSP &var_sp, ValueObjectSP &valobj_sp,
746                        const char *root_name) {
747     DumpValueObjectOptions options(m_varobj_options.GetAsDumpOptions());
748 
749     if (!valobj_sp->GetTargetSP()->GetDisplayRuntimeSupportValues() &&
750         valobj_sp->IsRuntimeSupportValue())
751       return;
752 
753     switch (var_sp->GetScope()) {
754     case eValueTypeVariableGlobal:
755       if (m_option_variable.show_scope)
756         s.PutCString("GLOBAL: ");
757       break;
758 
759     case eValueTypeVariableStatic:
760       if (m_option_variable.show_scope)
761         s.PutCString("STATIC: ");
762       break;
763 
764     case eValueTypeVariableArgument:
765       if (m_option_variable.show_scope)
766         s.PutCString("   ARG: ");
767       break;
768 
769     case eValueTypeVariableLocal:
770       if (m_option_variable.show_scope)
771         s.PutCString(" LOCAL: ");
772       break;
773 
774     case eValueTypeVariableThreadLocal:
775       if (m_option_variable.show_scope)
776         s.PutCString("THREAD: ");
777       break;
778 
779     default:
780       break;
781     }
782 
783     if (m_option_variable.show_decl) {
784       bool show_fullpaths = false;
785       bool show_module = true;
786       if (var_sp->DumpDeclaration(&s, show_fullpaths, show_module))
787         s.PutCString(": ");
788     }
789 
790     const Format format = m_option_format.GetFormat();
791     if (format != eFormatDefault)
792       options.SetFormat(format);
793 
794     options.SetRootValueObjectName(root_name);
795 
796     valobj_sp->Dump(s, options);
797   }
798 
799   static size_t GetVariableCallback(void *baton, const char *name,
800                                     VariableList &variable_list) {
801     size_t old_size = variable_list.GetSize();
802     Target *target = static_cast<Target *>(baton);
803     if (target)
804       target->GetImages().FindGlobalVariables(ConstString(name), UINT32_MAX,
805                                               variable_list);
806     return variable_list.GetSize() - old_size;
807   }
808 
809   Options *GetOptions() override { return &m_option_group; }
810 
811 protected:
812   void DumpGlobalVariableList(const ExecutionContext &exe_ctx,
813                               const SymbolContext &sc,
814                               const VariableList &variable_list, Stream &s) {
815     size_t count = variable_list.GetSize();
816     if (count > 0) {
817       if (sc.module_sp) {
818         if (sc.comp_unit) {
819           s.Printf("Global variables for %s in %s:\n",
820                    sc.comp_unit->GetPath().c_str(),
821                    sc.module_sp->GetFileSpec().GetPath().c_str());
822         } else {
823           s.Printf("Global variables for %s\n",
824                    sc.module_sp->GetFileSpec().GetPath().c_str());
825         }
826       } else if (sc.comp_unit) {
827         s.Printf("Global variables for %s\n", sc.comp_unit->GetPath().c_str());
828       }
829 
830       for (uint32_t i = 0; i < count; ++i) {
831         VariableSP var_sp(variable_list.GetVariableAtIndex(i));
832         if (var_sp) {
833           ValueObjectSP valobj_sp(ValueObjectVariable::Create(
834               exe_ctx.GetBestExecutionContextScope(), var_sp));
835 
836           if (valobj_sp)
837             DumpValueObject(s, var_sp, valobj_sp,
838                             var_sp->GetName().GetCString());
839         }
840       }
841     }
842   }
843 
844   bool DoExecute(Args &args, CommandReturnObject &result) override {
845     Target *target = m_exe_ctx.GetTargetPtr();
846     const size_t argc = args.GetArgumentCount();
847     Stream &s = result.GetOutputStream();
848 
849     if (argc > 0) {
850 
851       // TODO: Convert to entry-based iteration.  Requires converting
852       // DumpValueObject.
853       for (size_t idx = 0; idx < argc; ++idx) {
854         VariableList variable_list;
855         ValueObjectList valobj_list;
856 
857         const char *arg = args.GetArgumentAtIndex(idx);
858         size_t matches = 0;
859         bool use_var_name = false;
860         if (m_option_variable.use_regex) {
861           RegularExpression regex(llvm::StringRef::withNullAsEmpty(arg));
862           if (!regex.IsValid()) {
863             result.GetErrorStream().Printf(
864                 "error: invalid regular expression: '%s'\n", arg);
865             result.SetStatus(eReturnStatusFailed);
866             return false;
867           }
868           use_var_name = true;
869           target->GetImages().FindGlobalVariables(regex, UINT32_MAX,
870                                                   variable_list);
871           matches = variable_list.GetSize();
872         } else {
873           Status error(Variable::GetValuesForVariableExpressionPath(
874               arg, m_exe_ctx.GetBestExecutionContextScope(),
875               GetVariableCallback, target, variable_list, valobj_list));
876           matches = variable_list.GetSize();
877         }
878 
879         if (matches == 0) {
880           result.GetErrorStream().Printf(
881               "error: can't find global variable '%s'\n", arg);
882           result.SetStatus(eReturnStatusFailed);
883           return false;
884         } else {
885           for (uint32_t global_idx = 0; global_idx < matches; ++global_idx) {
886             VariableSP var_sp(variable_list.GetVariableAtIndex(global_idx));
887             if (var_sp) {
888               ValueObjectSP valobj_sp(
889                   valobj_list.GetValueObjectAtIndex(global_idx));
890               if (!valobj_sp)
891                 valobj_sp = ValueObjectVariable::Create(
892                     m_exe_ctx.GetBestExecutionContextScope(), var_sp);
893 
894               if (valobj_sp)
895                 DumpValueObject(s, var_sp, valobj_sp,
896                                 use_var_name ? var_sp->GetName().GetCString()
897                                              : arg);
898             }
899           }
900         }
901       }
902     } else {
903       const FileSpecList &compile_units =
904           m_option_compile_units.GetOptionValue().GetCurrentValue();
905       const FileSpecList &shlibs =
906           m_option_shared_libraries.GetOptionValue().GetCurrentValue();
907       SymbolContextList sc_list;
908       const size_t num_compile_units = compile_units.GetSize();
909       const size_t num_shlibs = shlibs.GetSize();
910       if (num_compile_units == 0 && num_shlibs == 0) {
911         bool success = false;
912         StackFrame *frame = m_exe_ctx.GetFramePtr();
913         CompileUnit *comp_unit = nullptr;
914         if (frame) {
915           SymbolContext sc = frame->GetSymbolContext(eSymbolContextCompUnit);
916           if (sc.comp_unit) {
917             const bool can_create = true;
918             VariableListSP comp_unit_varlist_sp(
919                 sc.comp_unit->GetVariableList(can_create));
920             if (comp_unit_varlist_sp) {
921               size_t count = comp_unit_varlist_sp->GetSize();
922               if (count > 0) {
923                 DumpGlobalVariableList(m_exe_ctx, sc, *comp_unit_varlist_sp, s);
924                 success = true;
925               }
926             }
927           }
928         }
929         if (!success) {
930           if (frame) {
931             if (comp_unit)
932               result.AppendErrorWithFormat(
933                   "no global variables in current compile unit: %s\n",
934                   comp_unit->GetPath().c_str());
935             else
936               result.AppendErrorWithFormat(
937                   "no debug information for frame %u\n",
938                   frame->GetFrameIndex());
939           } else
940             result.AppendError("'target variable' takes one or more global "
941                                "variable names as arguments\n");
942           result.SetStatus(eReturnStatusFailed);
943         }
944       } else {
945         SymbolContextList sc_list;
946         // We have one or more compile unit or shlib
947         if (num_shlibs > 0) {
948           for (size_t shlib_idx = 0; shlib_idx < num_shlibs; ++shlib_idx) {
949             const FileSpec module_file(shlibs.GetFileSpecAtIndex(shlib_idx));
950             ModuleSpec module_spec(module_file);
951 
952             ModuleSP module_sp(
953                 target->GetImages().FindFirstModule(module_spec));
954             if (module_sp) {
955               if (num_compile_units > 0) {
956                 for (size_t cu_idx = 0; cu_idx < num_compile_units; ++cu_idx)
957                   module_sp->FindCompileUnits(
958                       compile_units.GetFileSpecAtIndex(cu_idx), sc_list);
959               } else {
960                 SymbolContext sc;
961                 sc.module_sp = module_sp;
962                 sc_list.Append(sc);
963               }
964             } else {
965               // Didn't find matching shlib/module in target...
966               result.AppendErrorWithFormat(
967                   "target doesn't contain the specified shared library: %s\n",
968                   module_file.GetPath().c_str());
969             }
970           }
971         } else {
972           // No shared libraries, we just want to find globals for the compile
973           // units files that were specified
974           for (size_t cu_idx = 0; cu_idx < num_compile_units; ++cu_idx)
975             target->GetImages().FindCompileUnits(
976                 compile_units.GetFileSpecAtIndex(cu_idx), sc_list);
977         }
978 
979         const uint32_t num_scs = sc_list.GetSize();
980         if (num_scs > 0) {
981           SymbolContext sc;
982           for (uint32_t sc_idx = 0; sc_idx < num_scs; ++sc_idx) {
983             if (sc_list.GetContextAtIndex(sc_idx, sc)) {
984               if (sc.comp_unit) {
985                 const bool can_create = true;
986                 VariableListSP comp_unit_varlist_sp(
987                     sc.comp_unit->GetVariableList(can_create));
988                 if (comp_unit_varlist_sp)
989                   DumpGlobalVariableList(m_exe_ctx, sc, *comp_unit_varlist_sp,
990                                          s);
991               } else if (sc.module_sp) {
992                 // Get all global variables for this module
993                 lldb_private::RegularExpression all_globals_regex(
994                     llvm::StringRef(
995                         ".")); // Any global with at least one character
996                 VariableList variable_list;
997                 sc.module_sp->FindGlobalVariables(all_globals_regex, UINT32_MAX,
998                                                   variable_list);
999                 DumpGlobalVariableList(m_exe_ctx, sc, variable_list, s);
1000               }
1001             }
1002           }
1003         }
1004       }
1005     }
1006 
1007     if (m_interpreter.TruncationWarningNecessary()) {
1008       result.GetOutputStream().Printf(m_interpreter.TruncationWarningText(),
1009                                       m_cmd_name.c_str());
1010       m_interpreter.TruncationWarningGiven();
1011     }
1012 
1013     return result.Succeeded();
1014   }
1015 
1016   OptionGroupOptions m_option_group;
1017   OptionGroupVariable m_option_variable;
1018   OptionGroupFormat m_option_format;
1019   OptionGroupFileList m_option_compile_units;
1020   OptionGroupFileList m_option_shared_libraries;
1021   OptionGroupValueObjectDisplay m_varobj_options;
1022 };
1023 
1024 #pragma mark CommandObjectTargetModulesSearchPathsAdd
1025 
1026 class CommandObjectTargetModulesSearchPathsAdd : public CommandObjectParsed {
1027 public:
1028   CommandObjectTargetModulesSearchPathsAdd(CommandInterpreter &interpreter)
1029       : CommandObjectParsed(interpreter, "target modules search-paths add",
1030                             "Add new image search paths substitution pairs to "
1031                             "the current target.",
1032                             nullptr, eCommandRequiresTarget) {
1033     CommandArgumentEntry arg;
1034     CommandArgumentData old_prefix_arg;
1035     CommandArgumentData new_prefix_arg;
1036 
1037     // Define the first variant of this arg pair.
1038     old_prefix_arg.arg_type = eArgTypeOldPathPrefix;
1039     old_prefix_arg.arg_repetition = eArgRepeatPairPlus;
1040 
1041     // Define the first variant of this arg pair.
1042     new_prefix_arg.arg_type = eArgTypeNewPathPrefix;
1043     new_prefix_arg.arg_repetition = eArgRepeatPairPlus;
1044 
1045     // There are two required arguments that must always occur together, i.e.
1046     // an argument "pair".  Because they must always occur together, they are
1047     // treated as two variants of one argument rather than two independent
1048     // arguments.  Push them both into the first argument position for
1049     // m_arguments...
1050 
1051     arg.push_back(old_prefix_arg);
1052     arg.push_back(new_prefix_arg);
1053 
1054     m_arguments.push_back(arg);
1055   }
1056 
1057   ~CommandObjectTargetModulesSearchPathsAdd() override = default;
1058 
1059 protected:
1060   bool DoExecute(Args &command, CommandReturnObject &result) override {
1061     Target *target = &GetSelectedTarget();
1062     const size_t argc = command.GetArgumentCount();
1063     if (argc & 1) {
1064       result.AppendError("add requires an even number of arguments\n");
1065       result.SetStatus(eReturnStatusFailed);
1066     } else {
1067       for (size_t i = 0; i < argc; i += 2) {
1068         const char *from = command.GetArgumentAtIndex(i);
1069         const char *to = command.GetArgumentAtIndex(i + 1);
1070 
1071         if (from[0] && to[0]) {
1072           Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST);
1073           if (log) {
1074             LLDB_LOGF(log,
1075                       "target modules search path adding ImageSearchPath "
1076                       "pair: '%s' -> '%s'",
1077                       from, to);
1078           }
1079           bool last_pair = ((argc - i) == 2);
1080           target->GetImageSearchPathList().Append(
1081               ConstString(from), ConstString(to),
1082               last_pair); // Notify if this is the last pair
1083           result.SetStatus(eReturnStatusSuccessFinishNoResult);
1084         } else {
1085           if (from[0])
1086             result.AppendError("<path-prefix> can't be empty\n");
1087           else
1088             result.AppendError("<new-path-prefix> can't be empty\n");
1089           result.SetStatus(eReturnStatusFailed);
1090         }
1091       }
1092     }
1093     return result.Succeeded();
1094   }
1095 };
1096 
1097 #pragma mark CommandObjectTargetModulesSearchPathsClear
1098 
1099 class CommandObjectTargetModulesSearchPathsClear : public CommandObjectParsed {
1100 public:
1101   CommandObjectTargetModulesSearchPathsClear(CommandInterpreter &interpreter)
1102       : CommandObjectParsed(interpreter, "target modules search-paths clear",
1103                             "Clear all current image search path substitution "
1104                             "pairs from the current target.",
1105                             "target modules search-paths clear",
1106                             eCommandRequiresTarget) {}
1107 
1108   ~CommandObjectTargetModulesSearchPathsClear() override = default;
1109 
1110 protected:
1111   bool DoExecute(Args &command, CommandReturnObject &result) override {
1112     Target *target = &GetSelectedTarget();
1113     bool notify = true;
1114     target->GetImageSearchPathList().Clear(notify);
1115     result.SetStatus(eReturnStatusSuccessFinishNoResult);
1116     return result.Succeeded();
1117   }
1118 };
1119 
1120 #pragma mark CommandObjectTargetModulesSearchPathsInsert
1121 
1122 class CommandObjectTargetModulesSearchPathsInsert : public CommandObjectParsed {
1123 public:
1124   CommandObjectTargetModulesSearchPathsInsert(CommandInterpreter &interpreter)
1125       : CommandObjectParsed(interpreter, "target modules search-paths insert",
1126                             "Insert a new image search path substitution pair "
1127                             "into the current target at the specified index.",
1128                             nullptr, eCommandRequiresTarget) {
1129     CommandArgumentEntry arg1;
1130     CommandArgumentEntry arg2;
1131     CommandArgumentData index_arg;
1132     CommandArgumentData old_prefix_arg;
1133     CommandArgumentData new_prefix_arg;
1134 
1135     // Define the first and only variant of this arg.
1136     index_arg.arg_type = eArgTypeIndex;
1137     index_arg.arg_repetition = eArgRepeatPlain;
1138 
1139     // Put the one and only variant into the first arg for m_arguments:
1140     arg1.push_back(index_arg);
1141 
1142     // Define the first variant of this arg pair.
1143     old_prefix_arg.arg_type = eArgTypeOldPathPrefix;
1144     old_prefix_arg.arg_repetition = eArgRepeatPairPlus;
1145 
1146     // Define the first variant of this arg pair.
1147     new_prefix_arg.arg_type = eArgTypeNewPathPrefix;
1148     new_prefix_arg.arg_repetition = eArgRepeatPairPlus;
1149 
1150     // There are two required arguments that must always occur together, i.e.
1151     // an argument "pair".  Because they must always occur together, they are
1152     // treated as two variants of one argument rather than two independent
1153     // arguments.  Push them both into the same argument position for
1154     // m_arguments...
1155 
1156     arg2.push_back(old_prefix_arg);
1157     arg2.push_back(new_prefix_arg);
1158 
1159     // Add arguments to m_arguments.
1160     m_arguments.push_back(arg1);
1161     m_arguments.push_back(arg2);
1162   }
1163 
1164   ~CommandObjectTargetModulesSearchPathsInsert() override = default;
1165 
1166 protected:
1167   bool DoExecute(Args &command, CommandReturnObject &result) override {
1168     Target *target = &GetSelectedTarget();
1169     size_t argc = command.GetArgumentCount();
1170     // check for at least 3 arguments and an odd number of parameters
1171     if (argc >= 3 && argc & 1) {
1172       bool success = false;
1173 
1174       uint32_t insert_idx = StringConvert::ToUInt32(
1175           command.GetArgumentAtIndex(0), UINT32_MAX, 0, &success);
1176 
1177       if (!success) {
1178         result.AppendErrorWithFormat(
1179             "<index> parameter is not an integer: '%s'.\n",
1180             command.GetArgumentAtIndex(0));
1181         result.SetStatus(eReturnStatusFailed);
1182         return result.Succeeded();
1183       }
1184 
1185       // shift off the index
1186       command.Shift();
1187       argc = command.GetArgumentCount();
1188 
1189       for (uint32_t i = 0; i < argc; i += 2, ++insert_idx) {
1190         const char *from = command.GetArgumentAtIndex(i);
1191         const char *to = command.GetArgumentAtIndex(i + 1);
1192 
1193         if (from[0] && to[0]) {
1194           bool last_pair = ((argc - i) == 2);
1195           target->GetImageSearchPathList().Insert(
1196               ConstString(from), ConstString(to), insert_idx, last_pair);
1197           result.SetStatus(eReturnStatusSuccessFinishNoResult);
1198         } else {
1199           if (from[0])
1200             result.AppendError("<path-prefix> can't be empty\n");
1201           else
1202             result.AppendError("<new-path-prefix> can't be empty\n");
1203           result.SetStatus(eReturnStatusFailed);
1204           return false;
1205         }
1206       }
1207     } else {
1208       result.AppendError("insert requires at least three arguments\n");
1209       result.SetStatus(eReturnStatusFailed);
1210       return result.Succeeded();
1211     }
1212     return result.Succeeded();
1213   }
1214 };
1215 
1216 #pragma mark CommandObjectTargetModulesSearchPathsList
1217 
1218 class CommandObjectTargetModulesSearchPathsList : public CommandObjectParsed {
1219 public:
1220   CommandObjectTargetModulesSearchPathsList(CommandInterpreter &interpreter)
1221       : CommandObjectParsed(interpreter, "target modules search-paths list",
1222                             "List all current image search path substitution "
1223                             "pairs in the current target.",
1224                             "target modules search-paths list",
1225                             eCommandRequiresTarget) {}
1226 
1227   ~CommandObjectTargetModulesSearchPathsList() override = default;
1228 
1229 protected:
1230   bool DoExecute(Args &command, CommandReturnObject &result) override {
1231     Target *target = &GetSelectedTarget();
1232     if (command.GetArgumentCount() != 0) {
1233       result.AppendError("list takes no arguments\n");
1234       result.SetStatus(eReturnStatusFailed);
1235       return result.Succeeded();
1236     }
1237 
1238     target->GetImageSearchPathList().Dump(&result.GetOutputStream());
1239     result.SetStatus(eReturnStatusSuccessFinishResult);
1240     return result.Succeeded();
1241   }
1242 };
1243 
1244 #pragma mark CommandObjectTargetModulesSearchPathsQuery
1245 
1246 class CommandObjectTargetModulesSearchPathsQuery : public CommandObjectParsed {
1247 public:
1248   CommandObjectTargetModulesSearchPathsQuery(CommandInterpreter &interpreter)
1249       : CommandObjectParsed(
1250             interpreter, "target modules search-paths query",
1251             "Transform a path using the first applicable image search path.",
1252             nullptr, eCommandRequiresTarget) {
1253     CommandArgumentEntry arg;
1254     CommandArgumentData path_arg;
1255 
1256     // Define the first (and only) variant of this arg.
1257     path_arg.arg_type = eArgTypeDirectoryName;
1258     path_arg.arg_repetition = eArgRepeatPlain;
1259 
1260     // There is only one variant this argument could be; put it into the
1261     // argument entry.
1262     arg.push_back(path_arg);
1263 
1264     // Push the data for the first argument into the m_arguments vector.
1265     m_arguments.push_back(arg);
1266   }
1267 
1268   ~CommandObjectTargetModulesSearchPathsQuery() override = default;
1269 
1270 protected:
1271   bool DoExecute(Args &command, CommandReturnObject &result) override {
1272     Target *target = &GetSelectedTarget();
1273     if (command.GetArgumentCount() != 1) {
1274       result.AppendError("query requires one argument\n");
1275       result.SetStatus(eReturnStatusFailed);
1276       return result.Succeeded();
1277     }
1278 
1279     ConstString orig(command.GetArgumentAtIndex(0));
1280     ConstString transformed;
1281     if (target->GetImageSearchPathList().RemapPath(orig, transformed))
1282       result.GetOutputStream().Printf("%s\n", transformed.GetCString());
1283     else
1284       result.GetOutputStream().Printf("%s\n", orig.GetCString());
1285 
1286     result.SetStatus(eReturnStatusSuccessFinishResult);
1287     return result.Succeeded();
1288   }
1289 };
1290 
1291 // Static Helper functions
1292 static void DumpModuleArchitecture(Stream &strm, Module *module,
1293                                    bool full_triple, uint32_t width) {
1294   if (module) {
1295     StreamString arch_strm;
1296 
1297     if (full_triple)
1298       module->GetArchitecture().DumpTriple(arch_strm);
1299     else
1300       arch_strm.PutCString(module->GetArchitecture().GetArchitectureName());
1301     std::string arch_str = arch_strm.GetString();
1302 
1303     if (width)
1304       strm.Printf("%-*s", width, arch_str.c_str());
1305     else
1306       strm.PutCString(arch_str);
1307   }
1308 }
1309 
1310 static void DumpModuleUUID(Stream &strm, Module *module) {
1311   if (module && module->GetUUID().IsValid())
1312     module->GetUUID().Dump(&strm);
1313   else
1314     strm.PutCString("                                    ");
1315 }
1316 
1317 static uint32_t DumpCompileUnitLineTable(CommandInterpreter &interpreter,
1318                                          Stream &strm, Module *module,
1319                                          const FileSpec &file_spec,
1320                                          lldb::DescriptionLevel desc_level) {
1321   uint32_t num_matches = 0;
1322   if (module) {
1323     SymbolContextList sc_list;
1324     num_matches = module->ResolveSymbolContextsForFileSpec(
1325         file_spec, 0, false, eSymbolContextCompUnit, sc_list);
1326 
1327     for (uint32_t i = 0; i < num_matches; ++i) {
1328       SymbolContext sc;
1329       if (sc_list.GetContextAtIndex(i, sc)) {
1330         if (i > 0)
1331           strm << "\n\n";
1332 
1333         strm << "Line table for " << *static_cast<FileSpec *>(sc.comp_unit)
1334              << " in `" << module->GetFileSpec().GetFilename() << "\n";
1335         LineTable *line_table = sc.comp_unit->GetLineTable();
1336         if (line_table)
1337           line_table->GetDescription(
1338               &strm, interpreter.GetExecutionContext().GetTargetPtr(),
1339               desc_level);
1340         else
1341           strm << "No line table";
1342       }
1343     }
1344   }
1345   return num_matches;
1346 }
1347 
1348 static void DumpFullpath(Stream &strm, const FileSpec *file_spec_ptr,
1349                          uint32_t width) {
1350   if (file_spec_ptr) {
1351     if (width > 0) {
1352       std::string fullpath = file_spec_ptr->GetPath();
1353       strm.Printf("%-*s", width, fullpath.c_str());
1354       return;
1355     } else {
1356       file_spec_ptr->Dump(&strm);
1357       return;
1358     }
1359   }
1360   // Keep the width spacing correct if things go wrong...
1361   if (width > 0)
1362     strm.Printf("%-*s", width, "");
1363 }
1364 
1365 static void DumpDirectory(Stream &strm, const FileSpec *file_spec_ptr,
1366                           uint32_t width) {
1367   if (file_spec_ptr) {
1368     if (width > 0)
1369       strm.Printf("%-*s", width, file_spec_ptr->GetDirectory().AsCString(""));
1370     else
1371       file_spec_ptr->GetDirectory().Dump(&strm);
1372     return;
1373   }
1374   // Keep the width spacing correct if things go wrong...
1375   if (width > 0)
1376     strm.Printf("%-*s", width, "");
1377 }
1378 
1379 static void DumpBasename(Stream &strm, const FileSpec *file_spec_ptr,
1380                          uint32_t width) {
1381   if (file_spec_ptr) {
1382     if (width > 0)
1383       strm.Printf("%-*s", width, file_spec_ptr->GetFilename().AsCString(""));
1384     else
1385       file_spec_ptr->GetFilename().Dump(&strm);
1386     return;
1387   }
1388   // Keep the width spacing correct if things go wrong...
1389   if (width > 0)
1390     strm.Printf("%-*s", width, "");
1391 }
1392 
1393 static size_t DumpModuleObjfileHeaders(Stream &strm, ModuleList &module_list) {
1394   size_t num_dumped = 0;
1395   std::lock_guard<std::recursive_mutex> guard(module_list.GetMutex());
1396   const size_t num_modules = module_list.GetSize();
1397   if (num_modules > 0) {
1398     strm.Printf("Dumping headers for %" PRIu64 " module(s).\n",
1399                 static_cast<uint64_t>(num_modules));
1400     strm.IndentMore();
1401     for (size_t image_idx = 0; image_idx < num_modules; ++image_idx) {
1402       Module *module = module_list.GetModulePointerAtIndexUnlocked(image_idx);
1403       if (module) {
1404         if (num_dumped++ > 0) {
1405           strm.EOL();
1406           strm.EOL();
1407         }
1408         ObjectFile *objfile = module->GetObjectFile();
1409         if (objfile)
1410           objfile->Dump(&strm);
1411         else {
1412           strm.Format("No object file for module: {0:F}\n",
1413                       module->GetFileSpec());
1414         }
1415       }
1416     }
1417     strm.IndentLess();
1418   }
1419   return num_dumped;
1420 }
1421 
1422 static void DumpModuleSymtab(CommandInterpreter &interpreter, Stream &strm,
1423                              Module *module, SortOrder sort_order) {
1424   if (!module)
1425     return;
1426   if (Symtab *symtab = module->GetSymtab())
1427     symtab->Dump(&strm, interpreter.GetExecutionContext().GetTargetPtr(),
1428                  sort_order);
1429 }
1430 
1431 static void DumpModuleSections(CommandInterpreter &interpreter, Stream &strm,
1432                                Module *module) {
1433   if (module) {
1434     SectionList *section_list = module->GetSectionList();
1435     if (section_list) {
1436       strm.Printf("Sections for '%s' (%s):\n",
1437                   module->GetSpecificationDescription().c_str(),
1438                   module->GetArchitecture().GetArchitectureName());
1439       strm.IndentMore();
1440       section_list->Dump(&strm,
1441                          interpreter.GetExecutionContext().GetTargetPtr(), true,
1442                          UINT32_MAX);
1443       strm.IndentLess();
1444     }
1445   }
1446 }
1447 
1448 static bool DumpModuleSymbolFile(Stream &strm, Module *module) {
1449   if (module) {
1450     if (SymbolFile *symbol_file = module->GetSymbolFile(true)) {
1451       symbol_file->Dump(strm);
1452       return true;
1453     }
1454   }
1455   return false;
1456 }
1457 
1458 static void DumpAddress(ExecutionContextScope *exe_scope,
1459                         const Address &so_addr, bool verbose, Stream &strm) {
1460   strm.IndentMore();
1461   strm.Indent("    Address: ");
1462   so_addr.Dump(&strm, exe_scope, Address::DumpStyleModuleWithFileAddress);
1463   strm.PutCString(" (");
1464   so_addr.Dump(&strm, exe_scope, Address::DumpStyleSectionNameOffset);
1465   strm.PutCString(")\n");
1466   strm.Indent("    Summary: ");
1467   const uint32_t save_indent = strm.GetIndentLevel();
1468   strm.SetIndentLevel(save_indent + 13);
1469   so_addr.Dump(&strm, exe_scope, Address::DumpStyleResolvedDescription);
1470   strm.SetIndentLevel(save_indent);
1471   // Print out detailed address information when verbose is enabled
1472   if (verbose) {
1473     strm.EOL();
1474     so_addr.Dump(&strm, exe_scope, Address::DumpStyleDetailedSymbolContext);
1475   }
1476   strm.IndentLess();
1477 }
1478 
1479 static bool LookupAddressInModule(CommandInterpreter &interpreter, Stream &strm,
1480                                   Module *module, uint32_t resolve_mask,
1481                                   lldb::addr_t raw_addr, lldb::addr_t offset,
1482                                   bool verbose) {
1483   if (module) {
1484     lldb::addr_t addr = raw_addr - offset;
1485     Address so_addr;
1486     SymbolContext sc;
1487     Target *target = interpreter.GetExecutionContext().GetTargetPtr();
1488     if (target && !target->GetSectionLoadList().IsEmpty()) {
1489       if (!target->GetSectionLoadList().ResolveLoadAddress(addr, so_addr))
1490         return false;
1491       else if (so_addr.GetModule().get() != module)
1492         return false;
1493     } else {
1494       if (!module->ResolveFileAddress(addr, so_addr))
1495         return false;
1496     }
1497 
1498     ExecutionContextScope *exe_scope =
1499         interpreter.GetExecutionContext().GetBestExecutionContextScope();
1500     DumpAddress(exe_scope, so_addr, verbose, strm);
1501     //        strm.IndentMore();
1502     //        strm.Indent ("    Address: ");
1503     //        so_addr.Dump (&strm, exe_scope,
1504     //        Address::DumpStyleModuleWithFileAddress);
1505     //        strm.PutCString (" (");
1506     //        so_addr.Dump (&strm, exe_scope,
1507     //        Address::DumpStyleSectionNameOffset);
1508     //        strm.PutCString (")\n");
1509     //        strm.Indent ("    Summary: ");
1510     //        const uint32_t save_indent = strm.GetIndentLevel ();
1511     //        strm.SetIndentLevel (save_indent + 13);
1512     //        so_addr.Dump (&strm, exe_scope,
1513     //        Address::DumpStyleResolvedDescription);
1514     //        strm.SetIndentLevel (save_indent);
1515     //        // Print out detailed address information when verbose is enabled
1516     //        if (verbose)
1517     //        {
1518     //            strm.EOL();
1519     //            so_addr.Dump (&strm, exe_scope,
1520     //            Address::DumpStyleDetailedSymbolContext);
1521     //        }
1522     //        strm.IndentLess();
1523     return true;
1524   }
1525 
1526   return false;
1527 }
1528 
1529 static uint32_t LookupSymbolInModule(CommandInterpreter &interpreter,
1530                                      Stream &strm, Module *module,
1531                                      const char *name, bool name_is_regex,
1532                                      bool verbose) {
1533   if (!module)
1534     return 0;
1535 
1536   Symtab *symtab = module->GetSymtab();
1537   if (!symtab)
1538     return 0;
1539 
1540   SymbolContext sc;
1541   std::vector<uint32_t> match_indexes;
1542   ConstString symbol_name(name);
1543   uint32_t num_matches = 0;
1544   if (name_is_regex) {
1545     RegularExpression name_regexp(symbol_name.GetStringRef());
1546     num_matches = symtab->AppendSymbolIndexesMatchingRegExAndType(
1547         name_regexp, eSymbolTypeAny, match_indexes);
1548   } else {
1549     num_matches =
1550         symtab->AppendSymbolIndexesWithName(symbol_name, match_indexes);
1551   }
1552 
1553   if (num_matches > 0) {
1554     strm.Indent();
1555     strm.Printf("%u symbols match %s'%s' in ", num_matches,
1556                 name_is_regex ? "the regular expression " : "", name);
1557     DumpFullpath(strm, &module->GetFileSpec(), 0);
1558     strm.PutCString(":\n");
1559     strm.IndentMore();
1560     for (uint32_t i = 0; i < num_matches; ++i) {
1561       Symbol *symbol = symtab->SymbolAtIndex(match_indexes[i]);
1562       if (symbol && symbol->ValueIsAddress()) {
1563         DumpAddress(
1564             interpreter.GetExecutionContext().GetBestExecutionContextScope(),
1565             symbol->GetAddressRef(), verbose, strm);
1566       }
1567     }
1568     strm.IndentLess();
1569   }
1570   return num_matches;
1571 }
1572 
1573 static void DumpSymbolContextList(ExecutionContextScope *exe_scope,
1574                                   Stream &strm, SymbolContextList &sc_list,
1575                                   bool verbose) {
1576   strm.IndentMore();
1577 
1578   const uint32_t num_matches = sc_list.GetSize();
1579 
1580   for (uint32_t i = 0; i < num_matches; ++i) {
1581     SymbolContext sc;
1582     if (sc_list.GetContextAtIndex(i, sc)) {
1583       AddressRange range;
1584 
1585       sc.GetAddressRange(eSymbolContextEverything, 0, true, range);
1586 
1587       DumpAddress(exe_scope, range.GetBaseAddress(), verbose, strm);
1588     }
1589   }
1590   strm.IndentLess();
1591 }
1592 
1593 static size_t LookupFunctionInModule(CommandInterpreter &interpreter,
1594                                      Stream &strm, Module *module,
1595                                      const char *name, bool name_is_regex,
1596                                      bool include_inlines, bool include_symbols,
1597                                      bool verbose) {
1598   if (module && name && name[0]) {
1599     SymbolContextList sc_list;
1600     size_t num_matches = 0;
1601     if (name_is_regex) {
1602       RegularExpression function_name_regex((llvm::StringRef(name)));
1603       module->FindFunctions(function_name_regex, include_symbols,
1604                             include_inlines, sc_list);
1605     } else {
1606       ConstString function_name(name);
1607       module->FindFunctions(function_name, nullptr, eFunctionNameTypeAuto,
1608                             include_symbols, include_inlines, sc_list);
1609     }
1610     num_matches = sc_list.GetSize();
1611     if (num_matches) {
1612       strm.Indent();
1613       strm.Printf("%" PRIu64 " match%s found in ", (uint64_t)num_matches,
1614                   num_matches > 1 ? "es" : "");
1615       DumpFullpath(strm, &module->GetFileSpec(), 0);
1616       strm.PutCString(":\n");
1617       DumpSymbolContextList(
1618           interpreter.GetExecutionContext().GetBestExecutionContextScope(),
1619           strm, sc_list, verbose);
1620     }
1621     return num_matches;
1622   }
1623   return 0;
1624 }
1625 
1626 static size_t LookupTypeInModule(CommandInterpreter &interpreter, Stream &strm,
1627                                  Module *module, const char *name_cstr,
1628                                  bool name_is_regex) {
1629   TypeList type_list;
1630   if (module && name_cstr && name_cstr[0]) {
1631     const uint32_t max_num_matches = UINT32_MAX;
1632     size_t num_matches = 0;
1633     bool name_is_fully_qualified = false;
1634 
1635     ConstString name(name_cstr);
1636     llvm::DenseSet<lldb_private::SymbolFile *> searched_symbol_files;
1637     module->FindTypes(name, name_is_fully_qualified, max_num_matches,
1638                       searched_symbol_files, type_list);
1639 
1640     if (type_list.Empty())
1641       return 0;
1642 
1643     strm.Indent();
1644     strm.Printf("%" PRIu64 " match%s found in ", (uint64_t)num_matches,
1645                 num_matches > 1 ? "es" : "");
1646     DumpFullpath(strm, &module->GetFileSpec(), 0);
1647     strm.PutCString(":\n");
1648     for (TypeSP type_sp : type_list.Types()) {
1649       if (!type_sp)
1650         continue;
1651       // Resolve the clang type so that any forward references to types
1652       // that haven't yet been parsed will get parsed.
1653       type_sp->GetFullCompilerType();
1654       type_sp->GetDescription(&strm, eDescriptionLevelFull, true);
1655       // Print all typedef chains
1656       TypeSP typedef_type_sp(type_sp);
1657       TypeSP typedefed_type_sp(typedef_type_sp->GetTypedefType());
1658       while (typedefed_type_sp) {
1659         strm.EOL();
1660         strm.Printf("     typedef '%s': ",
1661                     typedef_type_sp->GetName().GetCString());
1662         typedefed_type_sp->GetFullCompilerType();
1663         typedefed_type_sp->GetDescription(&strm, eDescriptionLevelFull, true);
1664         typedef_type_sp = typedefed_type_sp;
1665         typedefed_type_sp = typedef_type_sp->GetTypedefType();
1666       }
1667     }
1668     strm.EOL();
1669   }
1670   return type_list.GetSize();
1671 }
1672 
1673 static size_t LookupTypeHere(CommandInterpreter &interpreter, Stream &strm,
1674                              Module &module, const char *name_cstr,
1675                              bool name_is_regex) {
1676   TypeList type_list;
1677   const uint32_t max_num_matches = UINT32_MAX;
1678   bool name_is_fully_qualified = false;
1679 
1680   ConstString name(name_cstr);
1681   llvm::DenseSet<SymbolFile *> searched_symbol_files;
1682   module.FindTypes(name, name_is_fully_qualified, max_num_matches,
1683                    searched_symbol_files, type_list);
1684 
1685   if (type_list.Empty())
1686     return 0;
1687 
1688   strm.Indent();
1689   strm.PutCString("Best match found in ");
1690   DumpFullpath(strm, &module.GetFileSpec(), 0);
1691   strm.PutCString(":\n");
1692 
1693   TypeSP type_sp(type_list.GetTypeAtIndex(0));
1694   if (type_sp) {
1695     // Resolve the clang type so that any forward references to types that
1696     // haven't yet been parsed will get parsed.
1697     type_sp->GetFullCompilerType();
1698     type_sp->GetDescription(&strm, eDescriptionLevelFull, true);
1699     // Print all typedef chains
1700     TypeSP typedef_type_sp(type_sp);
1701     TypeSP typedefed_type_sp(typedef_type_sp->GetTypedefType());
1702     while (typedefed_type_sp) {
1703       strm.EOL();
1704       strm.Printf("     typedef '%s': ",
1705                   typedef_type_sp->GetName().GetCString());
1706       typedefed_type_sp->GetFullCompilerType();
1707       typedefed_type_sp->GetDescription(&strm, eDescriptionLevelFull, true);
1708       typedef_type_sp = typedefed_type_sp;
1709       typedefed_type_sp = typedef_type_sp->GetTypedefType();
1710     }
1711   }
1712   strm.EOL();
1713   return type_list.GetSize();
1714 }
1715 
1716 static uint32_t LookupFileAndLineInModule(CommandInterpreter &interpreter,
1717                                           Stream &strm, Module *module,
1718                                           const FileSpec &file_spec,
1719                                           uint32_t line, bool check_inlines,
1720                                           bool verbose) {
1721   if (module && file_spec) {
1722     SymbolContextList sc_list;
1723     const uint32_t num_matches = module->ResolveSymbolContextsForFileSpec(
1724         file_spec, line, check_inlines, eSymbolContextEverything, sc_list);
1725     if (num_matches > 0) {
1726       strm.Indent();
1727       strm.Printf("%u match%s found in ", num_matches,
1728                   num_matches > 1 ? "es" : "");
1729       strm << file_spec;
1730       if (line > 0)
1731         strm.Printf(":%u", line);
1732       strm << " in ";
1733       DumpFullpath(strm, &module->GetFileSpec(), 0);
1734       strm.PutCString(":\n");
1735       DumpSymbolContextList(
1736           interpreter.GetExecutionContext().GetBestExecutionContextScope(),
1737           strm, sc_list, verbose);
1738       return num_matches;
1739     }
1740   }
1741   return 0;
1742 }
1743 
1744 static size_t FindModulesByName(Target *target, const char *module_name,
1745                                 ModuleList &module_list,
1746                                 bool check_global_list) {
1747   FileSpec module_file_spec(module_name);
1748   ModuleSpec module_spec(module_file_spec);
1749 
1750   const size_t initial_size = module_list.GetSize();
1751 
1752   if (check_global_list) {
1753     // Check the global list
1754     std::lock_guard<std::recursive_mutex> guard(
1755         Module::GetAllocationModuleCollectionMutex());
1756     const size_t num_modules = Module::GetNumberAllocatedModules();
1757     ModuleSP module_sp;
1758     for (size_t image_idx = 0; image_idx < num_modules; ++image_idx) {
1759       Module *module = Module::GetAllocatedModuleAtIndex(image_idx);
1760 
1761       if (module) {
1762         if (module->MatchesModuleSpec(module_spec)) {
1763           module_sp = module->shared_from_this();
1764           module_list.AppendIfNeeded(module_sp);
1765         }
1766       }
1767     }
1768   } else {
1769     if (target) {
1770       target->GetImages().FindModules(module_spec, module_list);
1771       const size_t num_matches = module_list.GetSize();
1772 
1773       // Not found in our module list for our target, check the main shared
1774       // module list in case it is a extra file used somewhere else
1775       if (num_matches == 0) {
1776         module_spec.GetArchitecture() = target->GetArchitecture();
1777         ModuleList::FindSharedModules(module_spec, module_list);
1778       }
1779     } else {
1780       ModuleList::FindSharedModules(module_spec, module_list);
1781     }
1782   }
1783 
1784   return module_list.GetSize() - initial_size;
1785 }
1786 
1787 #pragma mark CommandObjectTargetModulesModuleAutoComplete
1788 
1789 // A base command object class that can auto complete with module file
1790 // paths
1791 
1792 class CommandObjectTargetModulesModuleAutoComplete
1793     : public CommandObjectParsed {
1794 public:
1795   CommandObjectTargetModulesModuleAutoComplete(CommandInterpreter &interpreter,
1796                                                const char *name,
1797                                                const char *help,
1798                                                const char *syntax,
1799                                                uint32_t flags = 0)
1800       : CommandObjectParsed(interpreter, name, help, syntax, flags) {
1801     CommandArgumentEntry arg;
1802     CommandArgumentData file_arg;
1803 
1804     // Define the first (and only) variant of this arg.
1805     file_arg.arg_type = eArgTypeFilename;
1806     file_arg.arg_repetition = eArgRepeatStar;
1807 
1808     // There is only one variant this argument could be; put it into the
1809     // argument entry.
1810     arg.push_back(file_arg);
1811 
1812     // Push the data for the first argument into the m_arguments vector.
1813     m_arguments.push_back(arg);
1814   }
1815 
1816   ~CommandObjectTargetModulesModuleAutoComplete() override = default;
1817 
1818   void
1819   HandleArgumentCompletion(CompletionRequest &request,
1820                            OptionElementVector &opt_element_vector) override {
1821     CommandCompletions::InvokeCommonCompletionCallbacks(
1822         GetCommandInterpreter(), CommandCompletions::eModuleCompletion, request,
1823         nullptr);
1824   }
1825 };
1826 
1827 #pragma mark CommandObjectTargetModulesSourceFileAutoComplete
1828 
1829 // A base command object class that can auto complete with module source
1830 // file paths
1831 
1832 class CommandObjectTargetModulesSourceFileAutoComplete
1833     : public CommandObjectParsed {
1834 public:
1835   CommandObjectTargetModulesSourceFileAutoComplete(
1836       CommandInterpreter &interpreter, const char *name, const char *help,
1837       const char *syntax, uint32_t flags)
1838       : CommandObjectParsed(interpreter, name, help, syntax, flags) {
1839     CommandArgumentEntry arg;
1840     CommandArgumentData source_file_arg;
1841 
1842     // Define the first (and only) variant of this arg.
1843     source_file_arg.arg_type = eArgTypeSourceFile;
1844     source_file_arg.arg_repetition = eArgRepeatPlus;
1845 
1846     // There is only one variant this argument could be; put it into the
1847     // argument entry.
1848     arg.push_back(source_file_arg);
1849 
1850     // Push the data for the first argument into the m_arguments vector.
1851     m_arguments.push_back(arg);
1852   }
1853 
1854   ~CommandObjectTargetModulesSourceFileAutoComplete() override = default;
1855 
1856   void
1857   HandleArgumentCompletion(CompletionRequest &request,
1858                            OptionElementVector &opt_element_vector) override {
1859     CommandCompletions::InvokeCommonCompletionCallbacks(
1860         GetCommandInterpreter(), CommandCompletions::eSourceFileCompletion,
1861         request, nullptr);
1862   }
1863 };
1864 
1865 #pragma mark CommandObjectTargetModulesDumpObjfile
1866 
1867 class CommandObjectTargetModulesDumpObjfile
1868     : public CommandObjectTargetModulesModuleAutoComplete {
1869 public:
1870   CommandObjectTargetModulesDumpObjfile(CommandInterpreter &interpreter)
1871       : CommandObjectTargetModulesModuleAutoComplete(
1872             interpreter, "target modules dump objfile",
1873             "Dump the object file headers from one or more target modules.",
1874             nullptr, eCommandRequiresTarget) {}
1875 
1876   ~CommandObjectTargetModulesDumpObjfile() override = default;
1877 
1878 protected:
1879   bool DoExecute(Args &command, CommandReturnObject &result) override {
1880     Target *target = &GetSelectedTarget();
1881 
1882     uint32_t addr_byte_size = target->GetArchitecture().GetAddressByteSize();
1883     result.GetOutputStream().SetAddressByteSize(addr_byte_size);
1884     result.GetErrorStream().SetAddressByteSize(addr_byte_size);
1885 
1886     size_t num_dumped = 0;
1887     if (command.GetArgumentCount() == 0) {
1888       // Dump all headers for all modules images
1889       num_dumped = DumpModuleObjfileHeaders(result.GetOutputStream(),
1890                                             target->GetImages());
1891       if (num_dumped == 0) {
1892         result.AppendError("the target has no associated executable images");
1893         result.SetStatus(eReturnStatusFailed);
1894       }
1895     } else {
1896       // Find the modules that match the basename or full path.
1897       ModuleList module_list;
1898       const char *arg_cstr;
1899       for (int arg_idx = 0;
1900            (arg_cstr = command.GetArgumentAtIndex(arg_idx)) != nullptr;
1901            ++arg_idx) {
1902         size_t num_matched =
1903             FindModulesByName(target, arg_cstr, module_list, true);
1904         if (num_matched == 0) {
1905           result.AppendWarningWithFormat(
1906               "Unable to find an image that matches '%s'.\n", arg_cstr);
1907         }
1908       }
1909       // Dump all the modules we found.
1910       num_dumped =
1911           DumpModuleObjfileHeaders(result.GetOutputStream(), module_list);
1912     }
1913 
1914     if (num_dumped > 0) {
1915       result.SetStatus(eReturnStatusSuccessFinishResult);
1916     } else {
1917       result.AppendError("no matching executable images found");
1918       result.SetStatus(eReturnStatusFailed);
1919     }
1920     return result.Succeeded();
1921   }
1922 };
1923 
1924 #pragma mark CommandObjectTargetModulesDumpSymtab
1925 
1926 static constexpr OptionEnumValueElement g_sort_option_enumeration[] = {
1927     {
1928         eSortOrderNone,
1929         "none",
1930         "No sorting, use the original symbol table order.",
1931     },
1932     {
1933         eSortOrderByAddress,
1934         "address",
1935         "Sort output by symbol address.",
1936     },
1937     {
1938         eSortOrderByName,
1939         "name",
1940         "Sort output by symbol name.",
1941     },
1942 };
1943 
1944 #define LLDB_OPTIONS_target_modules_dump_symtab
1945 #include "CommandOptions.inc"
1946 
1947 class CommandObjectTargetModulesDumpSymtab
1948     : public CommandObjectTargetModulesModuleAutoComplete {
1949 public:
1950   CommandObjectTargetModulesDumpSymtab(CommandInterpreter &interpreter)
1951       : CommandObjectTargetModulesModuleAutoComplete(
1952             interpreter, "target modules dump symtab",
1953             "Dump the symbol table from one or more target modules.", nullptr,
1954             eCommandRequiresTarget),
1955         m_options() {}
1956 
1957   ~CommandObjectTargetModulesDumpSymtab() override = default;
1958 
1959   Options *GetOptions() override { return &m_options; }
1960 
1961   class CommandOptions : public Options {
1962   public:
1963     CommandOptions() : Options(), m_sort_order(eSortOrderNone) {}
1964 
1965     ~CommandOptions() override = default;
1966 
1967     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1968                           ExecutionContext *execution_context) override {
1969       Status error;
1970       const int short_option = m_getopt_table[option_idx].val;
1971 
1972       switch (short_option) {
1973       case 's':
1974         m_sort_order = (SortOrder)OptionArgParser::ToOptionEnum(
1975             option_arg, GetDefinitions()[option_idx].enum_values,
1976             eSortOrderNone, error);
1977         break;
1978 
1979       default:
1980         llvm_unreachable("Unimplemented option");
1981       }
1982       return error;
1983     }
1984 
1985     void OptionParsingStarting(ExecutionContext *execution_context) override {
1986       m_sort_order = eSortOrderNone;
1987     }
1988 
1989     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
1990       return llvm::makeArrayRef(g_target_modules_dump_symtab_options);
1991     }
1992 
1993     SortOrder m_sort_order;
1994   };
1995 
1996 protected:
1997   bool DoExecute(Args &command, CommandReturnObject &result) override {
1998     Target *target = &GetSelectedTarget();
1999     uint32_t num_dumped = 0;
2000 
2001     uint32_t addr_byte_size = target->GetArchitecture().GetAddressByteSize();
2002     result.GetOutputStream().SetAddressByteSize(addr_byte_size);
2003     result.GetErrorStream().SetAddressByteSize(addr_byte_size);
2004 
2005     if (command.GetArgumentCount() == 0) {
2006       // Dump all sections for all modules images
2007       std::lock_guard<std::recursive_mutex> guard(
2008           target->GetImages().GetMutex());
2009       const size_t num_modules = target->GetImages().GetSize();
2010       if (num_modules > 0) {
2011         result.GetOutputStream().Printf("Dumping symbol table for %" PRIu64
2012                                         " modules.\n",
2013                                         (uint64_t)num_modules);
2014         for (size_t image_idx = 0; image_idx < num_modules; ++image_idx) {
2015           if (num_dumped > 0) {
2016             result.GetOutputStream().EOL();
2017             result.GetOutputStream().EOL();
2018           }
2019           if (m_interpreter.WasInterrupted())
2020             break;
2021           num_dumped++;
2022           DumpModuleSymtab(
2023               m_interpreter, result.GetOutputStream(),
2024               target->GetImages().GetModulePointerAtIndexUnlocked(image_idx),
2025               m_options.m_sort_order);
2026         }
2027       } else {
2028         result.AppendError("the target has no associated executable images");
2029         result.SetStatus(eReturnStatusFailed);
2030         return false;
2031       }
2032     } else {
2033       // Dump specified images (by basename or fullpath)
2034       const char *arg_cstr;
2035       for (int arg_idx = 0;
2036            (arg_cstr = command.GetArgumentAtIndex(arg_idx)) != nullptr;
2037            ++arg_idx) {
2038         ModuleList module_list;
2039         const size_t num_matches =
2040             FindModulesByName(target, arg_cstr, module_list, true);
2041         if (num_matches > 0) {
2042           for (size_t i = 0; i < num_matches; ++i) {
2043             Module *module = module_list.GetModulePointerAtIndex(i);
2044             if (module) {
2045               if (num_dumped > 0) {
2046                 result.GetOutputStream().EOL();
2047                 result.GetOutputStream().EOL();
2048               }
2049               if (m_interpreter.WasInterrupted())
2050                 break;
2051               num_dumped++;
2052               DumpModuleSymtab(m_interpreter, result.GetOutputStream(), module,
2053                                m_options.m_sort_order);
2054             }
2055           }
2056         } else
2057           result.AppendWarningWithFormat(
2058               "Unable to find an image that matches '%s'.\n", arg_cstr);
2059       }
2060     }
2061 
2062     if (num_dumped > 0)
2063       result.SetStatus(eReturnStatusSuccessFinishResult);
2064     else {
2065       result.AppendError("no matching executable images found");
2066       result.SetStatus(eReturnStatusFailed);
2067     }
2068     return result.Succeeded();
2069   }
2070 
2071   CommandOptions m_options;
2072 };
2073 
2074 #pragma mark CommandObjectTargetModulesDumpSections
2075 
2076 // Image section dumping command
2077 
2078 class CommandObjectTargetModulesDumpSections
2079     : public CommandObjectTargetModulesModuleAutoComplete {
2080 public:
2081   CommandObjectTargetModulesDumpSections(CommandInterpreter &interpreter)
2082       : CommandObjectTargetModulesModuleAutoComplete(
2083             interpreter, "target modules dump sections",
2084             "Dump the sections from one or more target modules.",
2085             //"target modules dump sections [<file1> ...]")
2086             nullptr, eCommandRequiresTarget) {}
2087 
2088   ~CommandObjectTargetModulesDumpSections() override = default;
2089 
2090 protected:
2091   bool DoExecute(Args &command, CommandReturnObject &result) override {
2092     Target *target = &GetSelectedTarget();
2093     uint32_t num_dumped = 0;
2094 
2095     uint32_t addr_byte_size = target->GetArchitecture().GetAddressByteSize();
2096     result.GetOutputStream().SetAddressByteSize(addr_byte_size);
2097     result.GetErrorStream().SetAddressByteSize(addr_byte_size);
2098 
2099     if (command.GetArgumentCount() == 0) {
2100       // Dump all sections for all modules images
2101       const size_t num_modules = target->GetImages().GetSize();
2102       if (num_modules > 0) {
2103         result.GetOutputStream().Printf("Dumping sections for %" PRIu64
2104                                         " modules.\n",
2105                                         (uint64_t)num_modules);
2106         for (size_t image_idx = 0; image_idx < num_modules; ++image_idx) {
2107           if (m_interpreter.WasInterrupted())
2108             break;
2109           num_dumped++;
2110           DumpModuleSections(
2111               m_interpreter, result.GetOutputStream(),
2112               target->GetImages().GetModulePointerAtIndex(image_idx));
2113         }
2114       } else {
2115         result.AppendError("the target has no associated executable images");
2116         result.SetStatus(eReturnStatusFailed);
2117         return false;
2118       }
2119     } else {
2120       // Dump specified images (by basename or fullpath)
2121       const char *arg_cstr;
2122       for (int arg_idx = 0;
2123            (arg_cstr = command.GetArgumentAtIndex(arg_idx)) != nullptr;
2124            ++arg_idx) {
2125         ModuleList module_list;
2126         const size_t num_matches =
2127             FindModulesByName(target, arg_cstr, module_list, true);
2128         if (num_matches > 0) {
2129           for (size_t i = 0; i < num_matches; ++i) {
2130             if (m_interpreter.WasInterrupted())
2131               break;
2132             Module *module = module_list.GetModulePointerAtIndex(i);
2133             if (module) {
2134               num_dumped++;
2135               DumpModuleSections(m_interpreter, result.GetOutputStream(),
2136                                  module);
2137             }
2138           }
2139         } else {
2140           // Check the global list
2141           std::lock_guard<std::recursive_mutex> guard(
2142               Module::GetAllocationModuleCollectionMutex());
2143 
2144           result.AppendWarningWithFormat(
2145               "Unable to find an image that matches '%s'.\n", arg_cstr);
2146         }
2147       }
2148     }
2149 
2150     if (num_dumped > 0)
2151       result.SetStatus(eReturnStatusSuccessFinishResult);
2152     else {
2153       result.AppendError("no matching executable images found");
2154       result.SetStatus(eReturnStatusFailed);
2155     }
2156     return result.Succeeded();
2157   }
2158 };
2159 
2160 #pragma mark CommandObjectTargetModulesDumpSections
2161 
2162 // Clang AST dumping command
2163 
2164 class CommandObjectTargetModulesDumpClangAST
2165     : public CommandObjectTargetModulesModuleAutoComplete {
2166 public:
2167   CommandObjectTargetModulesDumpClangAST(CommandInterpreter &interpreter)
2168       : CommandObjectTargetModulesModuleAutoComplete(
2169             interpreter, "target modules dump ast",
2170             "Dump the clang ast for a given module's symbol file.",
2171             //"target modules dump ast [<file1> ...]")
2172             nullptr, eCommandRequiresTarget) {}
2173 
2174   ~CommandObjectTargetModulesDumpClangAST() override = default;
2175 
2176 protected:
2177   bool DoExecute(Args &command, CommandReturnObject &result) override {
2178     Target *target = &GetSelectedTarget();
2179 
2180     const size_t num_modules = target->GetImages().GetSize();
2181     if (num_modules == 0) {
2182       result.AppendError("the target has no associated executable images");
2183       result.SetStatus(eReturnStatusFailed);
2184       return false;
2185     }
2186 
2187     if (command.GetArgumentCount() == 0) {
2188       // Dump all ASTs for all modules images
2189       result.GetOutputStream().Printf("Dumping clang ast for %" PRIu64
2190                                       " modules.\n",
2191                                       (uint64_t)num_modules);
2192       for (size_t image_idx = 0; image_idx < num_modules; ++image_idx) {
2193         if (m_interpreter.WasInterrupted())
2194           break;
2195         Module *m = target->GetImages().GetModulePointerAtIndex(image_idx);
2196         if (SymbolFile *sf = m->GetSymbolFile())
2197           sf->DumpClangAST(result.GetOutputStream());
2198       }
2199       result.SetStatus(eReturnStatusSuccessFinishResult);
2200       return true;
2201     }
2202 
2203     // Dump specified ASTs (by basename or fullpath)
2204     for (const Args::ArgEntry &arg : command.entries()) {
2205       ModuleList module_list;
2206       const size_t num_matches =
2207           FindModulesByName(target, arg.c_str(), module_list, true);
2208       if (num_matches == 0) {
2209         // Check the global list
2210         std::lock_guard<std::recursive_mutex> guard(
2211             Module::GetAllocationModuleCollectionMutex());
2212 
2213         result.AppendWarningWithFormat(
2214             "Unable to find an image that matches '%s'.\n", arg.c_str());
2215         continue;
2216       }
2217 
2218       for (size_t i = 0; i < num_matches; ++i) {
2219         if (m_interpreter.WasInterrupted())
2220           break;
2221         Module *m = module_list.GetModulePointerAtIndex(i);
2222         if (SymbolFile *sf = m->GetSymbolFile())
2223           sf->DumpClangAST(result.GetOutputStream());
2224       }
2225     }
2226     result.SetStatus(eReturnStatusSuccessFinishResult);
2227     return true;
2228   }
2229 };
2230 
2231 #pragma mark CommandObjectTargetModulesDumpSymfile
2232 
2233 // Image debug symbol dumping command
2234 
2235 class CommandObjectTargetModulesDumpSymfile
2236     : public CommandObjectTargetModulesModuleAutoComplete {
2237 public:
2238   CommandObjectTargetModulesDumpSymfile(CommandInterpreter &interpreter)
2239       : CommandObjectTargetModulesModuleAutoComplete(
2240             interpreter, "target modules dump symfile",
2241             "Dump the debug symbol file for one or more target modules.",
2242             //"target modules dump symfile [<file1> ...]")
2243             nullptr, eCommandRequiresTarget) {}
2244 
2245   ~CommandObjectTargetModulesDumpSymfile() override = default;
2246 
2247 protected:
2248   bool DoExecute(Args &command, CommandReturnObject &result) override {
2249     Target *target = &GetSelectedTarget();
2250     uint32_t num_dumped = 0;
2251 
2252     uint32_t addr_byte_size = target->GetArchitecture().GetAddressByteSize();
2253     result.GetOutputStream().SetAddressByteSize(addr_byte_size);
2254     result.GetErrorStream().SetAddressByteSize(addr_byte_size);
2255 
2256     if (command.GetArgumentCount() == 0) {
2257       // Dump all sections for all modules images
2258       const ModuleList &target_modules = target->GetImages();
2259       std::lock_guard<std::recursive_mutex> guard(target_modules.GetMutex());
2260       const size_t num_modules = target_modules.GetSize();
2261       if (num_modules > 0) {
2262         result.GetOutputStream().Printf("Dumping debug symbols for %" PRIu64
2263                                         " modules.\n",
2264                                         (uint64_t)num_modules);
2265         for (uint32_t image_idx = 0; image_idx < num_modules; ++image_idx) {
2266           if (m_interpreter.WasInterrupted())
2267             break;
2268           if (DumpModuleSymbolFile(
2269                   result.GetOutputStream(),
2270                   target_modules.GetModulePointerAtIndexUnlocked(image_idx)))
2271             num_dumped++;
2272         }
2273       } else {
2274         result.AppendError("the target has no associated executable images");
2275         result.SetStatus(eReturnStatusFailed);
2276         return false;
2277       }
2278     } else {
2279       // Dump specified images (by basename or fullpath)
2280       const char *arg_cstr;
2281       for (int arg_idx = 0;
2282            (arg_cstr = command.GetArgumentAtIndex(arg_idx)) != nullptr;
2283            ++arg_idx) {
2284         ModuleList module_list;
2285         const size_t num_matches =
2286             FindModulesByName(target, arg_cstr, module_list, true);
2287         if (num_matches > 0) {
2288           for (size_t i = 0; i < num_matches; ++i) {
2289             if (m_interpreter.WasInterrupted())
2290               break;
2291             Module *module = module_list.GetModulePointerAtIndex(i);
2292             if (module) {
2293               if (DumpModuleSymbolFile(result.GetOutputStream(), module))
2294                 num_dumped++;
2295             }
2296           }
2297         } else
2298           result.AppendWarningWithFormat(
2299               "Unable to find an image that matches '%s'.\n", arg_cstr);
2300       }
2301     }
2302 
2303     if (num_dumped > 0)
2304       result.SetStatus(eReturnStatusSuccessFinishResult);
2305     else {
2306       result.AppendError("no matching executable images found");
2307       result.SetStatus(eReturnStatusFailed);
2308     }
2309     return result.Succeeded();
2310   }
2311 };
2312 
2313 #pragma mark CommandObjectTargetModulesDumpLineTable
2314 #define LLDB_OPTIONS_target_modules_dump
2315 #include "CommandOptions.inc"
2316 
2317 // Image debug line table dumping command
2318 
2319 class CommandObjectTargetModulesDumpLineTable
2320     : public CommandObjectTargetModulesSourceFileAutoComplete {
2321 public:
2322   CommandObjectTargetModulesDumpLineTable(CommandInterpreter &interpreter)
2323       : CommandObjectTargetModulesSourceFileAutoComplete(
2324             interpreter, "target modules dump line-table",
2325             "Dump the line table for one or more compilation units.", nullptr,
2326             eCommandRequiresTarget) {}
2327 
2328   ~CommandObjectTargetModulesDumpLineTable() override = default;
2329 
2330   Options *GetOptions() override { return &m_options; }
2331 
2332 protected:
2333   bool DoExecute(Args &command, CommandReturnObject &result) override {
2334     Target *target = m_exe_ctx.GetTargetPtr();
2335     uint32_t total_num_dumped = 0;
2336 
2337     uint32_t addr_byte_size = target->GetArchitecture().GetAddressByteSize();
2338     result.GetOutputStream().SetAddressByteSize(addr_byte_size);
2339     result.GetErrorStream().SetAddressByteSize(addr_byte_size);
2340 
2341     if (command.GetArgumentCount() == 0) {
2342       result.AppendError("file option must be specified.");
2343       result.SetStatus(eReturnStatusFailed);
2344       return result.Succeeded();
2345     } else {
2346       // Dump specified images (by basename or fullpath)
2347       const char *arg_cstr;
2348       for (int arg_idx = 0;
2349            (arg_cstr = command.GetArgumentAtIndex(arg_idx)) != nullptr;
2350            ++arg_idx) {
2351         FileSpec file_spec(arg_cstr);
2352 
2353         const ModuleList &target_modules = target->GetImages();
2354         std::lock_guard<std::recursive_mutex> guard(target_modules.GetMutex());
2355         const size_t num_modules = target_modules.GetSize();
2356         if (num_modules > 0) {
2357           uint32_t num_dumped = 0;
2358           for (uint32_t i = 0; i < num_modules; ++i) {
2359             if (m_interpreter.WasInterrupted())
2360               break;
2361             if (DumpCompileUnitLineTable(
2362                     m_interpreter, result.GetOutputStream(),
2363                     target_modules.GetModulePointerAtIndexUnlocked(i),
2364                     file_spec,
2365                     m_options.m_verbose ? eDescriptionLevelFull
2366                                         : eDescriptionLevelBrief))
2367               num_dumped++;
2368           }
2369           if (num_dumped == 0)
2370             result.AppendWarningWithFormat(
2371                 "No source filenames matched '%s'.\n", arg_cstr);
2372           else
2373             total_num_dumped += num_dumped;
2374         }
2375       }
2376     }
2377 
2378     if (total_num_dumped > 0)
2379       result.SetStatus(eReturnStatusSuccessFinishResult);
2380     else {
2381       result.AppendError("no source filenames matched any command arguments");
2382       result.SetStatus(eReturnStatusFailed);
2383     }
2384     return result.Succeeded();
2385   }
2386 
2387   class CommandOptions : public Options {
2388   public:
2389     CommandOptions() : Options() { OptionParsingStarting(nullptr); }
2390 
2391     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
2392                           ExecutionContext *execution_context) override {
2393       assert(option_idx == 0 && "We only have one option.");
2394       m_verbose = true;
2395 
2396       return Status();
2397     }
2398 
2399     void OptionParsingStarting(ExecutionContext *execution_context) override {
2400       m_verbose = false;
2401     }
2402 
2403     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
2404       return llvm::makeArrayRef(g_target_modules_dump_options);
2405     }
2406 
2407     bool m_verbose;
2408   };
2409 
2410   CommandOptions m_options;
2411 };
2412 
2413 #pragma mark CommandObjectTargetModulesDump
2414 
2415 // Dump multi-word command for target modules
2416 
2417 class CommandObjectTargetModulesDump : public CommandObjectMultiword {
2418 public:
2419   // Constructors and Destructors
2420   CommandObjectTargetModulesDump(CommandInterpreter &interpreter)
2421       : CommandObjectMultiword(
2422             interpreter, "target modules dump",
2423             "Commands for dumping information about one or "
2424             "more target modules.",
2425             "target modules dump "
2426             "[headers|symtab|sections|ast|symfile|line-table] "
2427             "[<file1> <file2> ...]") {
2428     LoadSubCommand("objfile",
2429                    CommandObjectSP(
2430                        new CommandObjectTargetModulesDumpObjfile(interpreter)));
2431     LoadSubCommand(
2432         "symtab",
2433         CommandObjectSP(new CommandObjectTargetModulesDumpSymtab(interpreter)));
2434     LoadSubCommand("sections",
2435                    CommandObjectSP(new CommandObjectTargetModulesDumpSections(
2436                        interpreter)));
2437     LoadSubCommand("symfile",
2438                    CommandObjectSP(
2439                        new CommandObjectTargetModulesDumpSymfile(interpreter)));
2440     LoadSubCommand(
2441         "ast", CommandObjectSP(
2442                    new CommandObjectTargetModulesDumpClangAST(interpreter)));
2443     LoadSubCommand("line-table",
2444                    CommandObjectSP(new CommandObjectTargetModulesDumpLineTable(
2445                        interpreter)));
2446   }
2447 
2448   ~CommandObjectTargetModulesDump() override = default;
2449 };
2450 
2451 class CommandObjectTargetModulesAdd : public CommandObjectParsed {
2452 public:
2453   CommandObjectTargetModulesAdd(CommandInterpreter &interpreter)
2454       : CommandObjectParsed(interpreter, "target modules add",
2455                             "Add a new module to the current target's modules.",
2456                             "target modules add [<module>]",
2457                             eCommandRequiresTarget),
2458         m_option_group(), m_symbol_file(LLDB_OPT_SET_1, false, "symfile", 's',
2459                                         0, eArgTypeFilename,
2460                                         "Fullpath to a stand alone debug "
2461                                         "symbols file for when debug symbols "
2462                                         "are not in the executable.") {
2463     m_option_group.Append(&m_uuid_option_group, LLDB_OPT_SET_ALL,
2464                           LLDB_OPT_SET_1);
2465     m_option_group.Append(&m_symbol_file, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
2466     m_option_group.Finalize();
2467   }
2468 
2469   ~CommandObjectTargetModulesAdd() override = default;
2470 
2471   Options *GetOptions() override { return &m_option_group; }
2472 
2473   void
2474   HandleArgumentCompletion(CompletionRequest &request,
2475                            OptionElementVector &opt_element_vector) override {
2476     CommandCompletions::InvokeCommonCompletionCallbacks(
2477         GetCommandInterpreter(), CommandCompletions::eDiskFileCompletion,
2478         request, nullptr);
2479   }
2480 
2481 protected:
2482   OptionGroupOptions m_option_group;
2483   OptionGroupUUID m_uuid_option_group;
2484   OptionGroupFile m_symbol_file;
2485 
2486   bool DoExecute(Args &args, CommandReturnObject &result) override {
2487     Target *target = &GetSelectedTarget();
2488     bool flush = false;
2489 
2490     const size_t argc = args.GetArgumentCount();
2491     if (argc == 0) {
2492       if (m_uuid_option_group.GetOptionValue().OptionWasSet()) {
2493         // We are given a UUID only, go locate the file
2494         ModuleSpec module_spec;
2495         module_spec.GetUUID() =
2496             m_uuid_option_group.GetOptionValue().GetCurrentValue();
2497         if (m_symbol_file.GetOptionValue().OptionWasSet())
2498           module_spec.GetSymbolFileSpec() =
2499               m_symbol_file.GetOptionValue().GetCurrentValue();
2500         if (Symbols::DownloadObjectAndSymbolFile(module_spec)) {
2501           ModuleSP module_sp(
2502               target->GetOrCreateModule(module_spec, true /* notify */));
2503           if (module_sp) {
2504             result.SetStatus(eReturnStatusSuccessFinishResult);
2505             return true;
2506           } else {
2507             StreamString strm;
2508             module_spec.GetUUID().Dump(&strm);
2509             if (module_spec.GetFileSpec()) {
2510               if (module_spec.GetSymbolFileSpec()) {
2511                 result.AppendErrorWithFormat(
2512                     "Unable to create the executable or symbol file with "
2513                     "UUID %s with path %s and symbol file %s",
2514                     strm.GetData(), module_spec.GetFileSpec().GetPath().c_str(),
2515                     module_spec.GetSymbolFileSpec().GetPath().c_str());
2516               } else {
2517                 result.AppendErrorWithFormat(
2518                     "Unable to create the executable or symbol file with "
2519                     "UUID %s with path %s",
2520                     strm.GetData(),
2521                     module_spec.GetFileSpec().GetPath().c_str());
2522               }
2523             } else {
2524               result.AppendErrorWithFormat("Unable to create the executable "
2525                                            "or symbol file with UUID %s",
2526                                            strm.GetData());
2527             }
2528             result.SetStatus(eReturnStatusFailed);
2529             return false;
2530           }
2531         } else {
2532           StreamString strm;
2533           module_spec.GetUUID().Dump(&strm);
2534           result.AppendErrorWithFormat(
2535               "Unable to locate the executable or symbol file with UUID %s",
2536               strm.GetData());
2537           result.SetStatus(eReturnStatusFailed);
2538           return false;
2539         }
2540       } else {
2541         result.AppendError(
2542             "one or more executable image paths must be specified");
2543         result.SetStatus(eReturnStatusFailed);
2544         return false;
2545       }
2546     } else {
2547       for (auto &entry : args.entries()) {
2548         if (entry.ref().empty())
2549           continue;
2550 
2551         FileSpec file_spec(entry.ref());
2552         if (FileSystem::Instance().Exists(file_spec)) {
2553           ModuleSpec module_spec(file_spec);
2554           if (m_uuid_option_group.GetOptionValue().OptionWasSet())
2555             module_spec.GetUUID() =
2556                 m_uuid_option_group.GetOptionValue().GetCurrentValue();
2557           if (m_symbol_file.GetOptionValue().OptionWasSet())
2558             module_spec.GetSymbolFileSpec() =
2559                 m_symbol_file.GetOptionValue().GetCurrentValue();
2560           if (!module_spec.GetArchitecture().IsValid())
2561             module_spec.GetArchitecture() = target->GetArchitecture();
2562           Status error;
2563           ModuleSP module_sp(target->GetOrCreateModule(
2564               module_spec, true /* notify */, &error));
2565           if (!module_sp) {
2566             const char *error_cstr = error.AsCString();
2567             if (error_cstr)
2568               result.AppendError(error_cstr);
2569             else
2570               result.AppendErrorWithFormat("unsupported module: %s",
2571                                            entry.c_str());
2572             result.SetStatus(eReturnStatusFailed);
2573             return false;
2574           } else {
2575             flush = true;
2576           }
2577           result.SetStatus(eReturnStatusSuccessFinishResult);
2578         } else {
2579           std::string resolved_path = file_spec.GetPath();
2580           result.SetStatus(eReturnStatusFailed);
2581           if (resolved_path != entry.ref()) {
2582             result.AppendErrorWithFormat(
2583                 "invalid module path '%s' with resolved path '%s'\n",
2584                 entry.ref().str().c_str(), resolved_path.c_str());
2585             break;
2586           }
2587           result.AppendErrorWithFormat("invalid module path '%s'\n",
2588                                        entry.c_str());
2589           break;
2590         }
2591       }
2592     }
2593 
2594     if (flush) {
2595       ProcessSP process = target->GetProcessSP();
2596       if (process)
2597         process->Flush();
2598     }
2599 
2600     return result.Succeeded();
2601   }
2602 };
2603 
2604 class CommandObjectTargetModulesLoad
2605     : public CommandObjectTargetModulesModuleAutoComplete {
2606 public:
2607   CommandObjectTargetModulesLoad(CommandInterpreter &interpreter)
2608       : CommandObjectTargetModulesModuleAutoComplete(
2609             interpreter, "target modules load",
2610             "Set the load addresses for one or more sections in a target "
2611             "module.",
2612             "target modules load [--file <module> --uuid <uuid>] <sect-name> "
2613             "<address> [<sect-name> <address> ....]",
2614             eCommandRequiresTarget),
2615         m_option_group(),
2616         m_file_option(LLDB_OPT_SET_1, false, "file", 'f', 0, eArgTypeName,
2617                       "Fullpath or basename for module to load.", ""),
2618         m_load_option(LLDB_OPT_SET_1, false, "load", 'l',
2619                       "Write file contents to the memory.", false, true),
2620         m_pc_option(LLDB_OPT_SET_1, false, "set-pc-to-entry", 'p',
2621                     "Set PC to the entry point."
2622                     " Only applicable with '--load' option.",
2623                     false, true),
2624         m_slide_option(LLDB_OPT_SET_1, false, "slide", 's', 0, eArgTypeOffset,
2625                        "Set the load address for all sections to be the "
2626                        "virtual address in the file plus the offset.",
2627                        0) {
2628     m_option_group.Append(&m_uuid_option_group, LLDB_OPT_SET_ALL,
2629                           LLDB_OPT_SET_1);
2630     m_option_group.Append(&m_file_option, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
2631     m_option_group.Append(&m_load_option, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
2632     m_option_group.Append(&m_pc_option, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
2633     m_option_group.Append(&m_slide_option, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
2634     m_option_group.Finalize();
2635   }
2636 
2637   ~CommandObjectTargetModulesLoad() override = default;
2638 
2639   Options *GetOptions() override { return &m_option_group; }
2640 
2641 protected:
2642   bool DoExecute(Args &args, CommandReturnObject &result) override {
2643     Target *target = &GetSelectedTarget();
2644     const bool load = m_load_option.GetOptionValue().GetCurrentValue();
2645     const bool set_pc = m_pc_option.GetOptionValue().GetCurrentValue();
2646 
2647     const size_t argc = args.GetArgumentCount();
2648     ModuleSpec module_spec;
2649     bool search_using_module_spec = false;
2650 
2651     // Allow "load" option to work without --file or --uuid option.
2652     if (load) {
2653       if (!m_file_option.GetOptionValue().OptionWasSet() &&
2654           !m_uuid_option_group.GetOptionValue().OptionWasSet()) {
2655         ModuleList &module_list = target->GetImages();
2656         if (module_list.GetSize() == 1) {
2657           search_using_module_spec = true;
2658           module_spec.GetFileSpec() =
2659               module_list.GetModuleAtIndex(0)->GetFileSpec();
2660         }
2661       }
2662     }
2663 
2664     if (m_file_option.GetOptionValue().OptionWasSet()) {
2665       search_using_module_spec = true;
2666       const char *arg_cstr = m_file_option.GetOptionValue().GetCurrentValue();
2667       const bool use_global_module_list = true;
2668       ModuleList module_list;
2669       const size_t num_matches = FindModulesByName(
2670           target, arg_cstr, module_list, use_global_module_list);
2671       if (num_matches == 1) {
2672         module_spec.GetFileSpec() =
2673             module_list.GetModuleAtIndex(0)->GetFileSpec();
2674       } else if (num_matches > 1) {
2675         search_using_module_spec = false;
2676         result.AppendErrorWithFormat(
2677             "more than 1 module matched by name '%s'\n", arg_cstr);
2678         result.SetStatus(eReturnStatusFailed);
2679       } else {
2680         search_using_module_spec = false;
2681         result.AppendErrorWithFormat("no object file for module '%s'\n",
2682                                      arg_cstr);
2683         result.SetStatus(eReturnStatusFailed);
2684       }
2685     }
2686 
2687     if (m_uuid_option_group.GetOptionValue().OptionWasSet()) {
2688       search_using_module_spec = true;
2689       module_spec.GetUUID() =
2690           m_uuid_option_group.GetOptionValue().GetCurrentValue();
2691     }
2692 
2693     if (search_using_module_spec) {
2694       ModuleList matching_modules;
2695       target->GetImages().FindModules(module_spec, matching_modules);
2696       const size_t num_matches = matching_modules.GetSize();
2697 
2698       char path[PATH_MAX];
2699       if (num_matches == 1) {
2700         Module *module = matching_modules.GetModulePointerAtIndex(0);
2701         if (module) {
2702           ObjectFile *objfile = module->GetObjectFile();
2703           if (objfile) {
2704             SectionList *section_list = module->GetSectionList();
2705             if (section_list) {
2706               bool changed = false;
2707               if (argc == 0) {
2708                 if (m_slide_option.GetOptionValue().OptionWasSet()) {
2709                   const addr_t slide =
2710                       m_slide_option.GetOptionValue().GetCurrentValue();
2711                   const bool slide_is_offset = true;
2712                   module->SetLoadAddress(*target, slide, slide_is_offset,
2713                                          changed);
2714                 } else {
2715                   result.AppendError("one or more section name + load "
2716                                      "address pair must be specified");
2717                   result.SetStatus(eReturnStatusFailed);
2718                   return false;
2719                 }
2720               } else {
2721                 if (m_slide_option.GetOptionValue().OptionWasSet()) {
2722                   result.AppendError("The \"--slide <offset>\" option can't "
2723                                      "be used in conjunction with setting "
2724                                      "section load addresses.\n");
2725                   result.SetStatus(eReturnStatusFailed);
2726                   return false;
2727                 }
2728 
2729                 for (size_t i = 0; i < argc; i += 2) {
2730                   const char *sect_name = args.GetArgumentAtIndex(i);
2731                   const char *load_addr_cstr = args.GetArgumentAtIndex(i + 1);
2732                   if (sect_name && load_addr_cstr) {
2733                     ConstString const_sect_name(sect_name);
2734                     bool success = false;
2735                     addr_t load_addr = StringConvert::ToUInt64(
2736                         load_addr_cstr, LLDB_INVALID_ADDRESS, 0, &success);
2737                     if (success) {
2738                       SectionSP section_sp(
2739                           section_list->FindSectionByName(const_sect_name));
2740                       if (section_sp) {
2741                         if (section_sp->IsThreadSpecific()) {
2742                           result.AppendErrorWithFormat(
2743                               "thread specific sections are not yet "
2744                               "supported (section '%s')\n",
2745                               sect_name);
2746                           result.SetStatus(eReturnStatusFailed);
2747                           break;
2748                         } else {
2749                           if (target->GetSectionLoadList()
2750                                   .SetSectionLoadAddress(section_sp, load_addr))
2751                             changed = true;
2752                           result.AppendMessageWithFormat(
2753                               "section '%s' loaded at 0x%" PRIx64 "\n",
2754                               sect_name, load_addr);
2755                         }
2756                       } else {
2757                         result.AppendErrorWithFormat("no section found that "
2758                                                      "matches the section "
2759                                                      "name '%s'\n",
2760                                                      sect_name);
2761                         result.SetStatus(eReturnStatusFailed);
2762                         break;
2763                       }
2764                     } else {
2765                       result.AppendErrorWithFormat(
2766                           "invalid load address string '%s'\n", load_addr_cstr);
2767                       result.SetStatus(eReturnStatusFailed);
2768                       break;
2769                     }
2770                   } else {
2771                     if (sect_name)
2772                       result.AppendError("section names must be followed by "
2773                                          "a load address.\n");
2774                     else
2775                       result.AppendError("one or more section name + load "
2776                                          "address pair must be specified.\n");
2777                     result.SetStatus(eReturnStatusFailed);
2778                     break;
2779                   }
2780                 }
2781               }
2782 
2783               if (changed) {
2784                 target->ModulesDidLoad(matching_modules);
2785                 Process *process = m_exe_ctx.GetProcessPtr();
2786                 if (process)
2787                   process->Flush();
2788               }
2789               if (load) {
2790                 ProcessSP process = target->CalculateProcess();
2791                 Address file_entry = objfile->GetEntryPointAddress();
2792                 if (!process) {
2793                   result.AppendError("No process");
2794                   return false;
2795                 }
2796                 if (set_pc && !file_entry.IsValid()) {
2797                   result.AppendError("No entry address in object file");
2798                   return false;
2799                 }
2800                 std::vector<ObjectFile::LoadableData> loadables(
2801                     objfile->GetLoadableData(*target));
2802                 if (loadables.size() == 0) {
2803                   result.AppendError("No loadable sections");
2804                   return false;
2805                 }
2806                 Status error = process->WriteObjectFile(std::move(loadables));
2807                 if (error.Fail()) {
2808                   result.AppendError(error.AsCString());
2809                   return false;
2810                 }
2811                 if (set_pc) {
2812                   ThreadList &thread_list = process->GetThreadList();
2813                   RegisterContextSP reg_context(
2814                       thread_list.GetSelectedThread()->GetRegisterContext());
2815                   addr_t file_entry_addr = file_entry.GetLoadAddress(target);
2816                   if (!reg_context->SetPC(file_entry_addr)) {
2817                     result.AppendErrorWithFormat("failed to set PC value to "
2818                                                  "0x%" PRIx64 "\n",
2819                                                  file_entry_addr);
2820                     result.SetStatus(eReturnStatusFailed);
2821                   }
2822                 }
2823               }
2824             } else {
2825               module->GetFileSpec().GetPath(path, sizeof(path));
2826               result.AppendErrorWithFormat("no sections in object file '%s'\n",
2827                                            path);
2828               result.SetStatus(eReturnStatusFailed);
2829             }
2830           } else {
2831             module->GetFileSpec().GetPath(path, sizeof(path));
2832             result.AppendErrorWithFormat("no object file for module '%s'\n",
2833                                          path);
2834             result.SetStatus(eReturnStatusFailed);
2835           }
2836         } else {
2837           FileSpec *module_spec_file = module_spec.GetFileSpecPtr();
2838           if (module_spec_file) {
2839             module_spec_file->GetPath(path, sizeof(path));
2840             result.AppendErrorWithFormat("invalid module '%s'.\n", path);
2841           } else
2842             result.AppendError("no module spec");
2843           result.SetStatus(eReturnStatusFailed);
2844         }
2845       } else {
2846         std::string uuid_str;
2847 
2848         if (module_spec.GetFileSpec())
2849           module_spec.GetFileSpec().GetPath(path, sizeof(path));
2850         else
2851           path[0] = '\0';
2852 
2853         if (module_spec.GetUUIDPtr())
2854           uuid_str = module_spec.GetUUID().GetAsString();
2855         if (num_matches > 1) {
2856           result.AppendErrorWithFormat(
2857               "multiple modules match%s%s%s%s:\n", path[0] ? " file=" : "",
2858               path, !uuid_str.empty() ? " uuid=" : "", uuid_str.c_str());
2859           for (size_t i = 0; i < num_matches; ++i) {
2860             if (matching_modules.GetModulePointerAtIndex(i)
2861                     ->GetFileSpec()
2862                     .GetPath(path, sizeof(path)))
2863               result.AppendMessageWithFormat("%s\n", path);
2864           }
2865         } else {
2866           result.AppendErrorWithFormat(
2867               "no modules were found  that match%s%s%s%s.\n",
2868               path[0] ? " file=" : "", path, !uuid_str.empty() ? " uuid=" : "",
2869               uuid_str.c_str());
2870         }
2871         result.SetStatus(eReturnStatusFailed);
2872       }
2873     } else {
2874       result.AppendError("either the \"--file <module>\" or the \"--uuid "
2875                          "<uuid>\" option must be specified.\n");
2876       result.SetStatus(eReturnStatusFailed);
2877       return false;
2878     }
2879     return result.Succeeded();
2880   }
2881 
2882   OptionGroupOptions m_option_group;
2883   OptionGroupUUID m_uuid_option_group;
2884   OptionGroupString m_file_option;
2885   OptionGroupBoolean m_load_option;
2886   OptionGroupBoolean m_pc_option;
2887   OptionGroupUInt64 m_slide_option;
2888 };
2889 
2890 // List images with associated information
2891 #define LLDB_OPTIONS_target_modules_list
2892 #include "CommandOptions.inc"
2893 
2894 class CommandObjectTargetModulesList : public CommandObjectParsed {
2895 public:
2896   class CommandOptions : public Options {
2897   public:
2898     CommandOptions()
2899         : Options(), m_format_array(), m_use_global_module_list(false),
2900           m_module_addr(LLDB_INVALID_ADDRESS) {}
2901 
2902     ~CommandOptions() override = default;
2903 
2904     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
2905                           ExecutionContext *execution_context) override {
2906       Status error;
2907 
2908       const int short_option = m_getopt_table[option_idx].val;
2909       if (short_option == 'g') {
2910         m_use_global_module_list = true;
2911       } else if (short_option == 'a') {
2912         m_module_addr = OptionArgParser::ToAddress(
2913             execution_context, option_arg, LLDB_INVALID_ADDRESS, &error);
2914       } else {
2915         unsigned long width = 0;
2916         option_arg.getAsInteger(0, width);
2917         m_format_array.push_back(std::make_pair(short_option, width));
2918       }
2919       return error;
2920     }
2921 
2922     void OptionParsingStarting(ExecutionContext *execution_context) override {
2923       m_format_array.clear();
2924       m_use_global_module_list = false;
2925       m_module_addr = LLDB_INVALID_ADDRESS;
2926     }
2927 
2928     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
2929       return llvm::makeArrayRef(g_target_modules_list_options);
2930     }
2931 
2932     // Instance variables to hold the values for command options.
2933     typedef std::vector<std::pair<char, uint32_t>> FormatWidthCollection;
2934     FormatWidthCollection m_format_array;
2935     bool m_use_global_module_list;
2936     lldb::addr_t m_module_addr;
2937   };
2938 
2939   CommandObjectTargetModulesList(CommandInterpreter &interpreter)
2940       : CommandObjectParsed(
2941             interpreter, "target modules list",
2942             "List current executable and dependent shared library images.",
2943             "target modules list [<cmd-options>]"),
2944         m_options() {}
2945 
2946   ~CommandObjectTargetModulesList() override = default;
2947 
2948   Options *GetOptions() override { return &m_options; }
2949 
2950 protected:
2951   bool DoExecute(Args &command, CommandReturnObject &result) override {
2952     Target *target = GetDebugger().GetSelectedTarget().get();
2953     const bool use_global_module_list = m_options.m_use_global_module_list;
2954     // Define a local module list here to ensure it lives longer than any
2955     // "locker" object which might lock its contents below (through the
2956     // "module_list_ptr" variable).
2957     ModuleList module_list;
2958     if (target == nullptr && !use_global_module_list) {
2959       result.AppendError("invalid target, create a debug target using the "
2960                          "'target create' command");
2961       result.SetStatus(eReturnStatusFailed);
2962       return false;
2963     } else {
2964       if (target) {
2965         uint32_t addr_byte_size =
2966             target->GetArchitecture().GetAddressByteSize();
2967         result.GetOutputStream().SetAddressByteSize(addr_byte_size);
2968         result.GetErrorStream().SetAddressByteSize(addr_byte_size);
2969       }
2970       // Dump all sections for all modules images
2971       Stream &strm = result.GetOutputStream();
2972 
2973       if (m_options.m_module_addr != LLDB_INVALID_ADDRESS) {
2974         if (target) {
2975           Address module_address;
2976           if (module_address.SetLoadAddress(m_options.m_module_addr, target)) {
2977             ModuleSP module_sp(module_address.GetModule());
2978             if (module_sp) {
2979               PrintModule(target, module_sp.get(), 0, strm);
2980               result.SetStatus(eReturnStatusSuccessFinishResult);
2981             } else {
2982               result.AppendErrorWithFormat(
2983                   "Couldn't find module matching address: 0x%" PRIx64 ".",
2984                   m_options.m_module_addr);
2985               result.SetStatus(eReturnStatusFailed);
2986             }
2987           } else {
2988             result.AppendErrorWithFormat(
2989                 "Couldn't find module containing address: 0x%" PRIx64 ".",
2990                 m_options.m_module_addr);
2991             result.SetStatus(eReturnStatusFailed);
2992           }
2993         } else {
2994           result.AppendError(
2995               "Can only look up modules by address with a valid target.");
2996           result.SetStatus(eReturnStatusFailed);
2997         }
2998         return result.Succeeded();
2999       }
3000 
3001       size_t num_modules = 0;
3002 
3003       // This locker will be locked on the mutex in module_list_ptr if it is
3004       // non-nullptr. Otherwise it will lock the
3005       // AllocationModuleCollectionMutex when accessing the global module list
3006       // directly.
3007       std::unique_lock<std::recursive_mutex> guard(
3008           Module::GetAllocationModuleCollectionMutex(), std::defer_lock);
3009 
3010       const ModuleList *module_list_ptr = nullptr;
3011       const size_t argc = command.GetArgumentCount();
3012       if (argc == 0) {
3013         if (use_global_module_list) {
3014           guard.lock();
3015           num_modules = Module::GetNumberAllocatedModules();
3016         } else {
3017           module_list_ptr = &target->GetImages();
3018         }
3019       } else {
3020         // TODO: Convert to entry based iteration.  Requires converting
3021         // FindModulesByName.
3022         for (size_t i = 0; i < argc; ++i) {
3023           // Dump specified images (by basename or fullpath)
3024           const char *arg_cstr = command.GetArgumentAtIndex(i);
3025           const size_t num_matches = FindModulesByName(
3026               target, arg_cstr, module_list, use_global_module_list);
3027           if (num_matches == 0) {
3028             if (argc == 1) {
3029               result.AppendErrorWithFormat("no modules found that match '%s'",
3030                                            arg_cstr);
3031               result.SetStatus(eReturnStatusFailed);
3032               return false;
3033             }
3034           }
3035         }
3036 
3037         module_list_ptr = &module_list;
3038       }
3039 
3040       std::unique_lock<std::recursive_mutex> lock;
3041       if (module_list_ptr != nullptr) {
3042         lock =
3043             std::unique_lock<std::recursive_mutex>(module_list_ptr->GetMutex());
3044 
3045         num_modules = module_list_ptr->GetSize();
3046       }
3047 
3048       if (num_modules > 0) {
3049         for (uint32_t image_idx = 0; image_idx < num_modules; ++image_idx) {
3050           ModuleSP module_sp;
3051           Module *module;
3052           if (module_list_ptr) {
3053             module_sp = module_list_ptr->GetModuleAtIndexUnlocked(image_idx);
3054             module = module_sp.get();
3055           } else {
3056             module = Module::GetAllocatedModuleAtIndex(image_idx);
3057             module_sp = module->shared_from_this();
3058           }
3059 
3060           const size_t indent = strm.Printf("[%3u] ", image_idx);
3061           PrintModule(target, module, indent, strm);
3062         }
3063         result.SetStatus(eReturnStatusSuccessFinishResult);
3064       } else {
3065         if (argc) {
3066           if (use_global_module_list)
3067             result.AppendError(
3068                 "the global module list has no matching modules");
3069           else
3070             result.AppendError("the target has no matching modules");
3071         } else {
3072           if (use_global_module_list)
3073             result.AppendError("the global module list is empty");
3074           else
3075             result.AppendError(
3076                 "the target has no associated executable images");
3077         }
3078         result.SetStatus(eReturnStatusFailed);
3079         return false;
3080       }
3081     }
3082     return result.Succeeded();
3083   }
3084 
3085   void PrintModule(Target *target, Module *module, int indent, Stream &strm) {
3086     if (module == nullptr) {
3087       strm.PutCString("Null module");
3088       return;
3089     }
3090 
3091     bool dump_object_name = false;
3092     if (m_options.m_format_array.empty()) {
3093       m_options.m_format_array.push_back(std::make_pair('u', 0));
3094       m_options.m_format_array.push_back(std::make_pair('h', 0));
3095       m_options.m_format_array.push_back(std::make_pair('f', 0));
3096       m_options.m_format_array.push_back(std::make_pair('S', 0));
3097     }
3098     const size_t num_entries = m_options.m_format_array.size();
3099     bool print_space = false;
3100     for (size_t i = 0; i < num_entries; ++i) {
3101       if (print_space)
3102         strm.PutChar(' ');
3103       print_space = true;
3104       const char format_char = m_options.m_format_array[i].first;
3105       uint32_t width = m_options.m_format_array[i].second;
3106       switch (format_char) {
3107       case 'A':
3108         DumpModuleArchitecture(strm, module, false, width);
3109         break;
3110 
3111       case 't':
3112         DumpModuleArchitecture(strm, module, true, width);
3113         break;
3114 
3115       case 'f':
3116         DumpFullpath(strm, &module->GetFileSpec(), width);
3117         dump_object_name = true;
3118         break;
3119 
3120       case 'd':
3121         DumpDirectory(strm, &module->GetFileSpec(), width);
3122         break;
3123 
3124       case 'b':
3125         DumpBasename(strm, &module->GetFileSpec(), width);
3126         dump_object_name = true;
3127         break;
3128 
3129       case 'h':
3130       case 'o':
3131         // Image header address
3132         {
3133           uint32_t addr_nibble_width =
3134               target ? (target->GetArchitecture().GetAddressByteSize() * 2)
3135                      : 16;
3136 
3137           ObjectFile *objfile = module->GetObjectFile();
3138           if (objfile) {
3139             Address base_addr(objfile->GetBaseAddress());
3140             if (base_addr.IsValid()) {
3141               if (target && !target->GetSectionLoadList().IsEmpty()) {
3142                 lldb::addr_t load_addr =
3143                     base_addr.GetLoadAddress(target);
3144                 if (load_addr == LLDB_INVALID_ADDRESS) {
3145                   base_addr.Dump(&strm, target,
3146                                    Address::DumpStyleModuleWithFileAddress,
3147                                    Address::DumpStyleFileAddress);
3148                 } else {
3149                   if (format_char == 'o') {
3150                     // Show the offset of slide for the image
3151                     strm.Printf(
3152                         "0x%*.*" PRIx64, addr_nibble_width, addr_nibble_width,
3153                         load_addr - base_addr.GetFileAddress());
3154                   } else {
3155                     // Show the load address of the image
3156                     strm.Printf("0x%*.*" PRIx64, addr_nibble_width,
3157                                 addr_nibble_width, load_addr);
3158                   }
3159                 }
3160                 break;
3161               }
3162               // The address was valid, but the image isn't loaded, output the
3163               // address in an appropriate format
3164               base_addr.Dump(&strm, target, Address::DumpStyleFileAddress);
3165               break;
3166             }
3167           }
3168           strm.Printf("%*s", addr_nibble_width + 2, "");
3169         }
3170         break;
3171 
3172       case 'r': {
3173         size_t ref_count = 0;
3174         ModuleSP module_sp(module->shared_from_this());
3175         if (module_sp) {
3176           // Take one away to make sure we don't count our local "module_sp"
3177           ref_count = module_sp.use_count() - 1;
3178         }
3179         if (width)
3180           strm.Printf("{%*" PRIu64 "}", width, (uint64_t)ref_count);
3181         else
3182           strm.Printf("{%" PRIu64 "}", (uint64_t)ref_count);
3183       } break;
3184 
3185       case 's':
3186       case 'S': {
3187         if (const SymbolFile *symbol_file = module->GetSymbolFile()) {
3188           const FileSpec symfile_spec =
3189               symbol_file->GetObjectFile()->GetFileSpec();
3190           if (format_char == 'S') {
3191             // Dump symbol file only if different from module file
3192             if (!symfile_spec || symfile_spec == module->GetFileSpec()) {
3193               print_space = false;
3194               break;
3195             }
3196             // Add a newline and indent past the index
3197             strm.Printf("\n%*s", indent, "");
3198           }
3199           DumpFullpath(strm, &symfile_spec, width);
3200           dump_object_name = true;
3201           break;
3202         }
3203         strm.Printf("%.*s", width, "<NONE>");
3204       } break;
3205 
3206       case 'm':
3207         strm.Format("{0:%c}", llvm::fmt_align(module->GetModificationTime(),
3208                                               llvm::AlignStyle::Left, width));
3209         break;
3210 
3211       case 'p':
3212         strm.Printf("%p", static_cast<void *>(module));
3213         break;
3214 
3215       case 'u':
3216         DumpModuleUUID(strm, module);
3217         break;
3218 
3219       default:
3220         break;
3221       }
3222     }
3223     if (dump_object_name) {
3224       const char *object_name = module->GetObjectName().GetCString();
3225       if (object_name)
3226         strm.Printf("(%s)", object_name);
3227     }
3228     strm.EOL();
3229   }
3230 
3231   CommandOptions m_options;
3232 };
3233 
3234 #pragma mark CommandObjectTargetModulesShowUnwind
3235 
3236 // Lookup unwind information in images
3237 #define LLDB_OPTIONS_target_modules_show_unwind
3238 #include "CommandOptions.inc"
3239 
3240 class CommandObjectTargetModulesShowUnwind : public CommandObjectParsed {
3241 public:
3242   enum {
3243     eLookupTypeInvalid = -1,
3244     eLookupTypeAddress = 0,
3245     eLookupTypeSymbol,
3246     eLookupTypeFunction,
3247     eLookupTypeFunctionOrSymbol,
3248     kNumLookupTypes
3249   };
3250 
3251   class CommandOptions : public Options {
3252   public:
3253     CommandOptions()
3254         : Options(), m_type(eLookupTypeInvalid), m_str(),
3255           m_addr(LLDB_INVALID_ADDRESS) {}
3256 
3257     ~CommandOptions() override = default;
3258 
3259     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
3260                           ExecutionContext *execution_context) override {
3261       Status error;
3262 
3263       const int short_option = m_getopt_table[option_idx].val;
3264 
3265       switch (short_option) {
3266       case 'a': {
3267         m_str = option_arg;
3268         m_type = eLookupTypeAddress;
3269         m_addr = OptionArgParser::ToAddress(execution_context, option_arg,
3270                                             LLDB_INVALID_ADDRESS, &error);
3271         if (m_addr == LLDB_INVALID_ADDRESS)
3272           error.SetErrorStringWithFormat("invalid address string '%s'",
3273                                          option_arg.str().c_str());
3274         break;
3275       }
3276 
3277       case 'n':
3278         m_str = option_arg;
3279         m_type = eLookupTypeFunctionOrSymbol;
3280         break;
3281 
3282       default:
3283         llvm_unreachable("Unimplemented option");
3284       }
3285 
3286       return error;
3287     }
3288 
3289     void OptionParsingStarting(ExecutionContext *execution_context) override {
3290       m_type = eLookupTypeInvalid;
3291       m_str.clear();
3292       m_addr = LLDB_INVALID_ADDRESS;
3293     }
3294 
3295     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
3296       return llvm::makeArrayRef(g_target_modules_show_unwind_options);
3297     }
3298 
3299     // Instance variables to hold the values for command options.
3300 
3301     int m_type;        // Should be a eLookupTypeXXX enum after parsing options
3302     std::string m_str; // Holds name lookup
3303     lldb::addr_t m_addr; // Holds the address to lookup
3304   };
3305 
3306   CommandObjectTargetModulesShowUnwind(CommandInterpreter &interpreter)
3307       : CommandObjectParsed(
3308             interpreter, "target modules show-unwind",
3309             "Show synthesized unwind instructions for a function.", nullptr,
3310             eCommandRequiresTarget | eCommandRequiresProcess |
3311                 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused),
3312         m_options() {}
3313 
3314   ~CommandObjectTargetModulesShowUnwind() override = default;
3315 
3316   Options *GetOptions() override { return &m_options; }
3317 
3318 protected:
3319   bool DoExecute(Args &command, CommandReturnObject &result) override {
3320     Target *target = m_exe_ctx.GetTargetPtr();
3321     Process *process = m_exe_ctx.GetProcessPtr();
3322     ABI *abi = nullptr;
3323     if (process)
3324       abi = process->GetABI().get();
3325 
3326     if (process == nullptr) {
3327       result.AppendError(
3328           "You must have a process running to use this command.");
3329       result.SetStatus(eReturnStatusFailed);
3330       return false;
3331     }
3332 
3333     ThreadList threads(process->GetThreadList());
3334     if (threads.GetSize() == 0) {
3335       result.AppendError("The process must be paused to use this command.");
3336       result.SetStatus(eReturnStatusFailed);
3337       return false;
3338     }
3339 
3340     ThreadSP thread(threads.GetThreadAtIndex(0));
3341     if (!thread) {
3342       result.AppendError("The process must be paused to use this command.");
3343       result.SetStatus(eReturnStatusFailed);
3344       return false;
3345     }
3346 
3347     SymbolContextList sc_list;
3348 
3349     if (m_options.m_type == eLookupTypeFunctionOrSymbol) {
3350       ConstString function_name(m_options.m_str.c_str());
3351       target->GetImages().FindFunctions(function_name, eFunctionNameTypeAuto,
3352                                         true, false, sc_list);
3353     } else if (m_options.m_type == eLookupTypeAddress && target) {
3354       Address addr;
3355       if (target->GetSectionLoadList().ResolveLoadAddress(m_options.m_addr,
3356                                                           addr)) {
3357         SymbolContext sc;
3358         ModuleSP module_sp(addr.GetModule());
3359         module_sp->ResolveSymbolContextForAddress(addr,
3360                                                   eSymbolContextEverything, sc);
3361         if (sc.function || sc.symbol) {
3362           sc_list.Append(sc);
3363         }
3364       }
3365     } else {
3366       result.AppendError(
3367           "address-expression or function name option must be specified.");
3368       result.SetStatus(eReturnStatusFailed);
3369       return false;
3370     }
3371 
3372     size_t num_matches = sc_list.GetSize();
3373     if (num_matches == 0) {
3374       result.AppendErrorWithFormat("no unwind data found that matches '%s'.",
3375                                    m_options.m_str.c_str());
3376       result.SetStatus(eReturnStatusFailed);
3377       return false;
3378     }
3379 
3380     for (uint32_t idx = 0; idx < num_matches; idx++) {
3381       SymbolContext sc;
3382       sc_list.GetContextAtIndex(idx, sc);
3383       if (sc.symbol == nullptr && sc.function == nullptr)
3384         continue;
3385       if (!sc.module_sp || sc.module_sp->GetObjectFile() == nullptr)
3386         continue;
3387       AddressRange range;
3388       if (!sc.GetAddressRange(eSymbolContextFunction | eSymbolContextSymbol, 0,
3389                               false, range))
3390         continue;
3391       if (!range.GetBaseAddress().IsValid())
3392         continue;
3393       ConstString funcname(sc.GetFunctionName());
3394       if (funcname.IsEmpty())
3395         continue;
3396       addr_t start_addr = range.GetBaseAddress().GetLoadAddress(target);
3397       if (abi)
3398         start_addr = abi->FixCodeAddress(start_addr);
3399 
3400       FuncUnwindersSP func_unwinders_sp(
3401           sc.module_sp->GetUnwindTable()
3402               .GetUncachedFuncUnwindersContainingAddress(start_addr, sc));
3403       if (!func_unwinders_sp)
3404         continue;
3405 
3406       result.GetOutputStream().Printf(
3407           "UNWIND PLANS for %s`%s (start addr 0x%" PRIx64 ")\n\n",
3408           sc.module_sp->GetPlatformFileSpec().GetFilename().AsCString(),
3409           funcname.AsCString(), start_addr);
3410 
3411       UnwindPlanSP non_callsite_unwind_plan =
3412           func_unwinders_sp->GetUnwindPlanAtNonCallSite(*target, *thread);
3413       if (non_callsite_unwind_plan) {
3414         result.GetOutputStream().Printf(
3415             "Asynchronous (not restricted to call-sites) UnwindPlan is '%s'\n",
3416             non_callsite_unwind_plan->GetSourceName().AsCString());
3417       }
3418       UnwindPlanSP callsite_unwind_plan =
3419           func_unwinders_sp->GetUnwindPlanAtCallSite(*target, *thread);
3420       if (callsite_unwind_plan) {
3421         result.GetOutputStream().Printf(
3422             "Synchronous (restricted to call-sites) UnwindPlan is '%s'\n",
3423             callsite_unwind_plan->GetSourceName().AsCString());
3424       }
3425       UnwindPlanSP fast_unwind_plan =
3426           func_unwinders_sp->GetUnwindPlanFastUnwind(*target, *thread);
3427       if (fast_unwind_plan) {
3428         result.GetOutputStream().Printf(
3429             "Fast UnwindPlan is '%s'\n",
3430             fast_unwind_plan->GetSourceName().AsCString());
3431       }
3432 
3433       result.GetOutputStream().Printf("\n");
3434 
3435       UnwindPlanSP assembly_sp =
3436           func_unwinders_sp->GetAssemblyUnwindPlan(*target, *thread);
3437       if (assembly_sp) {
3438         result.GetOutputStream().Printf(
3439             "Assembly language inspection UnwindPlan:\n");
3440         assembly_sp->Dump(result.GetOutputStream(), thread.get(),
3441                           LLDB_INVALID_ADDRESS);
3442         result.GetOutputStream().Printf("\n");
3443       }
3444 
3445       UnwindPlanSP of_unwind_sp =
3446           func_unwinders_sp->GetObjectFileUnwindPlan(*target);
3447       if (of_unwind_sp) {
3448         result.GetOutputStream().Printf("object file UnwindPlan:\n");
3449         of_unwind_sp->Dump(result.GetOutputStream(), thread.get(),
3450                            LLDB_INVALID_ADDRESS);
3451         result.GetOutputStream().Printf("\n");
3452       }
3453 
3454       UnwindPlanSP of_unwind_augmented_sp =
3455           func_unwinders_sp->GetObjectFileAugmentedUnwindPlan(*target,
3456                                                               *thread);
3457       if (of_unwind_augmented_sp) {
3458         result.GetOutputStream().Printf("object file augmented UnwindPlan:\n");
3459         of_unwind_augmented_sp->Dump(result.GetOutputStream(), thread.get(),
3460                                      LLDB_INVALID_ADDRESS);
3461         result.GetOutputStream().Printf("\n");
3462       }
3463 
3464       UnwindPlanSP ehframe_sp =
3465           func_unwinders_sp->GetEHFrameUnwindPlan(*target);
3466       if (ehframe_sp) {
3467         result.GetOutputStream().Printf("eh_frame UnwindPlan:\n");
3468         ehframe_sp->Dump(result.GetOutputStream(), thread.get(),
3469                          LLDB_INVALID_ADDRESS);
3470         result.GetOutputStream().Printf("\n");
3471       }
3472 
3473       UnwindPlanSP ehframe_augmented_sp =
3474           func_unwinders_sp->GetEHFrameAugmentedUnwindPlan(*target, *thread);
3475       if (ehframe_augmented_sp) {
3476         result.GetOutputStream().Printf("eh_frame augmented UnwindPlan:\n");
3477         ehframe_augmented_sp->Dump(result.GetOutputStream(), thread.get(),
3478                                    LLDB_INVALID_ADDRESS);
3479         result.GetOutputStream().Printf("\n");
3480       }
3481 
3482       if (UnwindPlanSP plan_sp =
3483               func_unwinders_sp->GetDebugFrameUnwindPlan(*target)) {
3484         result.GetOutputStream().Printf("debug_frame UnwindPlan:\n");
3485         plan_sp->Dump(result.GetOutputStream(), thread.get(),
3486                       LLDB_INVALID_ADDRESS);
3487         result.GetOutputStream().Printf("\n");
3488       }
3489 
3490       if (UnwindPlanSP plan_sp =
3491               func_unwinders_sp->GetDebugFrameAugmentedUnwindPlan(*target,
3492                                                                   *thread)) {
3493         result.GetOutputStream().Printf("debug_frame augmented UnwindPlan:\n");
3494         plan_sp->Dump(result.GetOutputStream(), thread.get(),
3495                       LLDB_INVALID_ADDRESS);
3496         result.GetOutputStream().Printf("\n");
3497       }
3498 
3499       UnwindPlanSP arm_unwind_sp =
3500           func_unwinders_sp->GetArmUnwindUnwindPlan(*target);
3501       if (arm_unwind_sp) {
3502         result.GetOutputStream().Printf("ARM.exidx unwind UnwindPlan:\n");
3503         arm_unwind_sp->Dump(result.GetOutputStream(), thread.get(),
3504                             LLDB_INVALID_ADDRESS);
3505         result.GetOutputStream().Printf("\n");
3506       }
3507 
3508       if (UnwindPlanSP symfile_plan_sp =
3509               func_unwinders_sp->GetSymbolFileUnwindPlan(*thread)) {
3510         result.GetOutputStream().Printf("Symbol file UnwindPlan:\n");
3511         symfile_plan_sp->Dump(result.GetOutputStream(), thread.get(),
3512                               LLDB_INVALID_ADDRESS);
3513         result.GetOutputStream().Printf("\n");
3514       }
3515 
3516       UnwindPlanSP compact_unwind_sp =
3517           func_unwinders_sp->GetCompactUnwindUnwindPlan(*target);
3518       if (compact_unwind_sp) {
3519         result.GetOutputStream().Printf("Compact unwind UnwindPlan:\n");
3520         compact_unwind_sp->Dump(result.GetOutputStream(), thread.get(),
3521                                 LLDB_INVALID_ADDRESS);
3522         result.GetOutputStream().Printf("\n");
3523       }
3524 
3525       if (fast_unwind_plan) {
3526         result.GetOutputStream().Printf("Fast UnwindPlan:\n");
3527         fast_unwind_plan->Dump(result.GetOutputStream(), thread.get(),
3528                                LLDB_INVALID_ADDRESS);
3529         result.GetOutputStream().Printf("\n");
3530       }
3531 
3532       ABISP abi_sp = process->GetABI();
3533       if (abi_sp) {
3534         UnwindPlan arch_default(lldb::eRegisterKindGeneric);
3535         if (abi_sp->CreateDefaultUnwindPlan(arch_default)) {
3536           result.GetOutputStream().Printf("Arch default UnwindPlan:\n");
3537           arch_default.Dump(result.GetOutputStream(), thread.get(),
3538                             LLDB_INVALID_ADDRESS);
3539           result.GetOutputStream().Printf("\n");
3540         }
3541 
3542         UnwindPlan arch_entry(lldb::eRegisterKindGeneric);
3543         if (abi_sp->CreateFunctionEntryUnwindPlan(arch_entry)) {
3544           result.GetOutputStream().Printf(
3545               "Arch default at entry point UnwindPlan:\n");
3546           arch_entry.Dump(result.GetOutputStream(), thread.get(),
3547                           LLDB_INVALID_ADDRESS);
3548           result.GetOutputStream().Printf("\n");
3549         }
3550       }
3551 
3552       result.GetOutputStream().Printf("\n");
3553     }
3554     return result.Succeeded();
3555   }
3556 
3557   CommandOptions m_options;
3558 };
3559 
3560 // Lookup information in images
3561 #define LLDB_OPTIONS_target_modules_lookup
3562 #include "CommandOptions.inc"
3563 
3564 class CommandObjectTargetModulesLookup : public CommandObjectParsed {
3565 public:
3566   enum {
3567     eLookupTypeInvalid = -1,
3568     eLookupTypeAddress = 0,
3569     eLookupTypeSymbol,
3570     eLookupTypeFileLine, // Line is optional
3571     eLookupTypeFunction,
3572     eLookupTypeFunctionOrSymbol,
3573     eLookupTypeType,
3574     kNumLookupTypes
3575   };
3576 
3577   class CommandOptions : public Options {
3578   public:
3579     CommandOptions() : Options() { OptionParsingStarting(nullptr); }
3580 
3581     ~CommandOptions() override = default;
3582 
3583     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
3584                           ExecutionContext *execution_context) override {
3585       Status error;
3586 
3587       const int short_option = m_getopt_table[option_idx].val;
3588 
3589       switch (short_option) {
3590       case 'a': {
3591         m_type = eLookupTypeAddress;
3592         m_addr = OptionArgParser::ToAddress(execution_context, option_arg,
3593                                             LLDB_INVALID_ADDRESS, &error);
3594       } break;
3595 
3596       case 'o':
3597         if (option_arg.getAsInteger(0, m_offset))
3598           error.SetErrorStringWithFormat("invalid offset string '%s'",
3599                                          option_arg.str().c_str());
3600         break;
3601 
3602       case 's':
3603         m_str = option_arg;
3604         m_type = eLookupTypeSymbol;
3605         break;
3606 
3607       case 'f':
3608         m_file.SetFile(option_arg, FileSpec::Style::native);
3609         m_type = eLookupTypeFileLine;
3610         break;
3611 
3612       case 'i':
3613         m_include_inlines = false;
3614         break;
3615 
3616       case 'l':
3617         if (option_arg.getAsInteger(0, m_line_number))
3618           error.SetErrorStringWithFormat("invalid line number string '%s'",
3619                                          option_arg.str().c_str());
3620         else if (m_line_number == 0)
3621           error.SetErrorString("zero is an invalid line number");
3622         m_type = eLookupTypeFileLine;
3623         break;
3624 
3625       case 'F':
3626         m_str = option_arg;
3627         m_type = eLookupTypeFunction;
3628         break;
3629 
3630       case 'n':
3631         m_str = option_arg;
3632         m_type = eLookupTypeFunctionOrSymbol;
3633         break;
3634 
3635       case 't':
3636         m_str = option_arg;
3637         m_type = eLookupTypeType;
3638         break;
3639 
3640       case 'v':
3641         m_verbose = true;
3642         break;
3643 
3644       case 'A':
3645         m_print_all = true;
3646         break;
3647 
3648       case 'r':
3649         m_use_regex = true;
3650         break;
3651       default:
3652         llvm_unreachable("Unimplemented option");
3653       }
3654 
3655       return error;
3656     }
3657 
3658     void OptionParsingStarting(ExecutionContext *execution_context) override {
3659       m_type = eLookupTypeInvalid;
3660       m_str.clear();
3661       m_file.Clear();
3662       m_addr = LLDB_INVALID_ADDRESS;
3663       m_offset = 0;
3664       m_line_number = 0;
3665       m_use_regex = false;
3666       m_include_inlines = true;
3667       m_verbose = false;
3668       m_print_all = false;
3669     }
3670 
3671     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
3672       return llvm::makeArrayRef(g_target_modules_lookup_options);
3673     }
3674 
3675     int m_type;        // Should be a eLookupTypeXXX enum after parsing options
3676     std::string m_str; // Holds name lookup
3677     FileSpec m_file;   // Files for file lookups
3678     lldb::addr_t m_addr; // Holds the address to lookup
3679     lldb::addr_t
3680         m_offset; // Subtract this offset from m_addr before doing lookups.
3681     uint32_t m_line_number; // Line number for file+line lookups
3682     bool m_use_regex;       // Name lookups in m_str are regular expressions.
3683     bool m_include_inlines; // Check for inline entries when looking up by
3684                             // file/line.
3685     bool m_verbose;         // Enable verbose lookup info
3686     bool m_print_all; // Print all matches, even in cases where there's a best
3687                       // match.
3688   };
3689 
3690   CommandObjectTargetModulesLookup(CommandInterpreter &interpreter)
3691       : CommandObjectParsed(interpreter, "target modules lookup",
3692                             "Look up information within executable and "
3693                             "dependent shared library images.",
3694                             nullptr, eCommandRequiresTarget),
3695         m_options() {
3696     CommandArgumentEntry arg;
3697     CommandArgumentData file_arg;
3698 
3699     // Define the first (and only) variant of this arg.
3700     file_arg.arg_type = eArgTypeFilename;
3701     file_arg.arg_repetition = eArgRepeatStar;
3702 
3703     // There is only one variant this argument could be; put it into the
3704     // argument entry.
3705     arg.push_back(file_arg);
3706 
3707     // Push the data for the first argument into the m_arguments vector.
3708     m_arguments.push_back(arg);
3709   }
3710 
3711   ~CommandObjectTargetModulesLookup() override = default;
3712 
3713   Options *GetOptions() override { return &m_options; }
3714 
3715   bool LookupHere(CommandInterpreter &interpreter, CommandReturnObject &result,
3716                   bool &syntax_error) {
3717     switch (m_options.m_type) {
3718     case eLookupTypeAddress:
3719     case eLookupTypeFileLine:
3720     case eLookupTypeFunction:
3721     case eLookupTypeFunctionOrSymbol:
3722     case eLookupTypeSymbol:
3723     default:
3724       return false;
3725     case eLookupTypeType:
3726       break;
3727     }
3728 
3729     StackFrameSP frame = m_exe_ctx.GetFrameSP();
3730 
3731     if (!frame)
3732       return false;
3733 
3734     const SymbolContext &sym_ctx(frame->GetSymbolContext(eSymbolContextModule));
3735 
3736     if (!sym_ctx.module_sp)
3737       return false;
3738 
3739     switch (m_options.m_type) {
3740     default:
3741       return false;
3742     case eLookupTypeType:
3743       if (!m_options.m_str.empty()) {
3744         if (LookupTypeHere(m_interpreter, result.GetOutputStream(),
3745                            *sym_ctx.module_sp, m_options.m_str.c_str(),
3746                            m_options.m_use_regex)) {
3747           result.SetStatus(eReturnStatusSuccessFinishResult);
3748           return true;
3749         }
3750       }
3751       break;
3752     }
3753 
3754     return true;
3755   }
3756 
3757   bool LookupInModule(CommandInterpreter &interpreter, Module *module,
3758                       CommandReturnObject &result, bool &syntax_error) {
3759     switch (m_options.m_type) {
3760     case eLookupTypeAddress:
3761       if (m_options.m_addr != LLDB_INVALID_ADDRESS) {
3762         if (LookupAddressInModule(
3763                 m_interpreter, result.GetOutputStream(), module,
3764                 eSymbolContextEverything |
3765                     (m_options.m_verbose
3766                          ? static_cast<int>(eSymbolContextVariable)
3767                          : 0),
3768                 m_options.m_addr, m_options.m_offset, m_options.m_verbose)) {
3769           result.SetStatus(eReturnStatusSuccessFinishResult);
3770           return true;
3771         }
3772       }
3773       break;
3774 
3775     case eLookupTypeSymbol:
3776       if (!m_options.m_str.empty()) {
3777         if (LookupSymbolInModule(m_interpreter, result.GetOutputStream(),
3778                                  module, m_options.m_str.c_str(),
3779                                  m_options.m_use_regex, m_options.m_verbose)) {
3780           result.SetStatus(eReturnStatusSuccessFinishResult);
3781           return true;
3782         }
3783       }
3784       break;
3785 
3786     case eLookupTypeFileLine:
3787       if (m_options.m_file) {
3788         if (LookupFileAndLineInModule(
3789                 m_interpreter, result.GetOutputStream(), module,
3790                 m_options.m_file, m_options.m_line_number,
3791                 m_options.m_include_inlines, m_options.m_verbose)) {
3792           result.SetStatus(eReturnStatusSuccessFinishResult);
3793           return true;
3794         }
3795       }
3796       break;
3797 
3798     case eLookupTypeFunctionOrSymbol:
3799     case eLookupTypeFunction:
3800       if (!m_options.m_str.empty()) {
3801         if (LookupFunctionInModule(
3802                 m_interpreter, result.GetOutputStream(), module,
3803                 m_options.m_str.c_str(), m_options.m_use_regex,
3804                 m_options.m_include_inlines,
3805                 m_options.m_type ==
3806                     eLookupTypeFunctionOrSymbol, // include symbols
3807                 m_options.m_verbose)) {
3808           result.SetStatus(eReturnStatusSuccessFinishResult);
3809           return true;
3810         }
3811       }
3812       break;
3813 
3814     case eLookupTypeType:
3815       if (!m_options.m_str.empty()) {
3816         if (LookupTypeInModule(m_interpreter, result.GetOutputStream(), module,
3817                                m_options.m_str.c_str(),
3818                                m_options.m_use_regex)) {
3819           result.SetStatus(eReturnStatusSuccessFinishResult);
3820           return true;
3821         }
3822       }
3823       break;
3824 
3825     default:
3826       m_options.GenerateOptionUsage(
3827           result.GetErrorStream(), this,
3828           GetCommandInterpreter().GetDebugger().GetTerminalWidth());
3829       syntax_error = true;
3830       break;
3831     }
3832 
3833     result.SetStatus(eReturnStatusFailed);
3834     return false;
3835   }
3836 
3837 protected:
3838   bool DoExecute(Args &command, CommandReturnObject &result) override {
3839     Target *target = &GetSelectedTarget();
3840     bool syntax_error = false;
3841     uint32_t i;
3842     uint32_t num_successful_lookups = 0;
3843     uint32_t addr_byte_size = target->GetArchitecture().GetAddressByteSize();
3844     result.GetOutputStream().SetAddressByteSize(addr_byte_size);
3845     result.GetErrorStream().SetAddressByteSize(addr_byte_size);
3846     // Dump all sections for all modules images
3847 
3848     if (command.GetArgumentCount() == 0) {
3849       ModuleSP current_module;
3850 
3851       // Where it is possible to look in the current symbol context first,
3852       // try that.  If this search was successful and --all was not passed,
3853       // don't print anything else.
3854       if (LookupHere(m_interpreter, result, syntax_error)) {
3855         result.GetOutputStream().EOL();
3856         num_successful_lookups++;
3857         if (!m_options.m_print_all) {
3858           result.SetStatus(eReturnStatusSuccessFinishResult);
3859           return result.Succeeded();
3860         }
3861       }
3862 
3863       // Dump all sections for all other modules
3864 
3865       const ModuleList &target_modules = target->GetImages();
3866       std::lock_guard<std::recursive_mutex> guard(target_modules.GetMutex());
3867       const size_t num_modules = target_modules.GetSize();
3868       if (num_modules > 0) {
3869         for (i = 0; i < num_modules && !syntax_error; ++i) {
3870           Module *module_pointer =
3871               target_modules.GetModulePointerAtIndexUnlocked(i);
3872 
3873           if (module_pointer != current_module.get() &&
3874               LookupInModule(m_interpreter,
3875                              target_modules.GetModulePointerAtIndexUnlocked(i),
3876                              result, syntax_error)) {
3877             result.GetOutputStream().EOL();
3878             num_successful_lookups++;
3879           }
3880         }
3881       } else {
3882         result.AppendError("the target has no associated executable images");
3883         result.SetStatus(eReturnStatusFailed);
3884         return false;
3885       }
3886     } else {
3887       // Dump specified images (by basename or fullpath)
3888       const char *arg_cstr;
3889       for (i = 0; (arg_cstr = command.GetArgumentAtIndex(i)) != nullptr &&
3890                   !syntax_error;
3891            ++i) {
3892         ModuleList module_list;
3893         const size_t num_matches =
3894             FindModulesByName(target, arg_cstr, module_list, false);
3895         if (num_matches > 0) {
3896           for (size_t j = 0; j < num_matches; ++j) {
3897             Module *module = module_list.GetModulePointerAtIndex(j);
3898             if (module) {
3899               if (LookupInModule(m_interpreter, module, result, syntax_error)) {
3900                 result.GetOutputStream().EOL();
3901                 num_successful_lookups++;
3902               }
3903             }
3904           }
3905         } else
3906           result.AppendWarningWithFormat(
3907               "Unable to find an image that matches '%s'.\n", arg_cstr);
3908       }
3909     }
3910 
3911     if (num_successful_lookups > 0)
3912       result.SetStatus(eReturnStatusSuccessFinishResult);
3913     else
3914       result.SetStatus(eReturnStatusFailed);
3915     return result.Succeeded();
3916   }
3917 
3918   CommandOptions m_options;
3919 };
3920 
3921 #pragma mark CommandObjectMultiwordImageSearchPaths
3922 
3923 // CommandObjectMultiwordImageSearchPaths
3924 
3925 class CommandObjectTargetModulesImageSearchPaths
3926     : public CommandObjectMultiword {
3927 public:
3928   CommandObjectTargetModulesImageSearchPaths(CommandInterpreter &interpreter)
3929       : CommandObjectMultiword(
3930             interpreter, "target modules search-paths",
3931             "Commands for managing module search paths for a target.",
3932             "target modules search-paths <subcommand> [<subcommand-options>]") {
3933     LoadSubCommand(
3934         "add", CommandObjectSP(
3935                    new CommandObjectTargetModulesSearchPathsAdd(interpreter)));
3936     LoadSubCommand(
3937         "clear", CommandObjectSP(new CommandObjectTargetModulesSearchPathsClear(
3938                      interpreter)));
3939     LoadSubCommand(
3940         "insert",
3941         CommandObjectSP(
3942             new CommandObjectTargetModulesSearchPathsInsert(interpreter)));
3943     LoadSubCommand(
3944         "list", CommandObjectSP(new CommandObjectTargetModulesSearchPathsList(
3945                     interpreter)));
3946     LoadSubCommand(
3947         "query", CommandObjectSP(new CommandObjectTargetModulesSearchPathsQuery(
3948                      interpreter)));
3949   }
3950 
3951   ~CommandObjectTargetModulesImageSearchPaths() override = default;
3952 };
3953 
3954 #pragma mark CommandObjectTargetModules
3955 
3956 // CommandObjectTargetModules
3957 
3958 class CommandObjectTargetModules : public CommandObjectMultiword {
3959 public:
3960   // Constructors and Destructors
3961   CommandObjectTargetModules(CommandInterpreter &interpreter)
3962       : CommandObjectMultiword(interpreter, "target modules",
3963                                "Commands for accessing information for one or "
3964                                "more target modules.",
3965                                "target modules <sub-command> ...") {
3966     LoadSubCommand(
3967         "add", CommandObjectSP(new CommandObjectTargetModulesAdd(interpreter)));
3968     LoadSubCommand("load", CommandObjectSP(new CommandObjectTargetModulesLoad(
3969                                interpreter)));
3970     LoadSubCommand("dump", CommandObjectSP(new CommandObjectTargetModulesDump(
3971                                interpreter)));
3972     LoadSubCommand("list", CommandObjectSP(new CommandObjectTargetModulesList(
3973                                interpreter)));
3974     LoadSubCommand(
3975         "lookup",
3976         CommandObjectSP(new CommandObjectTargetModulesLookup(interpreter)));
3977     LoadSubCommand(
3978         "search-paths",
3979         CommandObjectSP(
3980             new CommandObjectTargetModulesImageSearchPaths(interpreter)));
3981     LoadSubCommand(
3982         "show-unwind",
3983         CommandObjectSP(new CommandObjectTargetModulesShowUnwind(interpreter)));
3984   }
3985 
3986   ~CommandObjectTargetModules() override = default;
3987 
3988 private:
3989   // For CommandObjectTargetModules only
3990   DISALLOW_COPY_AND_ASSIGN(CommandObjectTargetModules);
3991 };
3992 
3993 class CommandObjectTargetSymbolsAdd : public CommandObjectParsed {
3994 public:
3995   CommandObjectTargetSymbolsAdd(CommandInterpreter &interpreter)
3996       : CommandObjectParsed(
3997             interpreter, "target symbols add",
3998             "Add a debug symbol file to one of the target's current modules by "
3999             "specifying a path to a debug symbols file, or using the options "
4000             "to specify a module to download symbols for.",
4001             "target symbols add <cmd-options> [<symfile>]",
4002             eCommandRequiresTarget),
4003         m_option_group(),
4004         m_file_option(
4005             LLDB_OPT_SET_1, false, "shlib", 's',
4006             CommandCompletions::eModuleCompletion, eArgTypeShlibName,
4007             "Fullpath or basename for module to find debug symbols for."),
4008         m_current_frame_option(
4009             LLDB_OPT_SET_2, false, "frame", 'F',
4010             "Locate the debug symbols the currently selected frame.", false,
4011             true)
4012 
4013   {
4014     m_option_group.Append(&m_uuid_option_group, LLDB_OPT_SET_ALL,
4015                           LLDB_OPT_SET_1);
4016     m_option_group.Append(&m_file_option, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4017     m_option_group.Append(&m_current_frame_option, LLDB_OPT_SET_2,
4018                           LLDB_OPT_SET_2);
4019     m_option_group.Finalize();
4020   }
4021 
4022   ~CommandObjectTargetSymbolsAdd() override = default;
4023 
4024   void
4025   HandleArgumentCompletion(CompletionRequest &request,
4026                            OptionElementVector &opt_element_vector) override {
4027     CommandCompletions::InvokeCommonCompletionCallbacks(
4028         GetCommandInterpreter(), CommandCompletions::eDiskFileCompletion,
4029         request, nullptr);
4030   }
4031 
4032   Options *GetOptions() override { return &m_option_group; }
4033 
4034 protected:
4035   bool AddModuleSymbols(Target *target, ModuleSpec &module_spec, bool &flush,
4036                         CommandReturnObject &result) {
4037     const FileSpec &symbol_fspec = module_spec.GetSymbolFileSpec();
4038     if (symbol_fspec) {
4039       char symfile_path[PATH_MAX];
4040       symbol_fspec.GetPath(symfile_path, sizeof(symfile_path));
4041 
4042       if (!module_spec.GetUUID().IsValid()) {
4043         if (!module_spec.GetFileSpec() && !module_spec.GetPlatformFileSpec())
4044           module_spec.GetFileSpec().GetFilename() = symbol_fspec.GetFilename();
4045       }
4046       // We now have a module that represents a symbol file that can be used
4047       // for a module that might exist in the current target, so we need to
4048       // find that module in the target
4049       ModuleList matching_module_list;
4050 
4051       size_t num_matches = 0;
4052       // First extract all module specs from the symbol file
4053       lldb_private::ModuleSpecList symfile_module_specs;
4054       if (ObjectFile::GetModuleSpecifications(module_spec.GetSymbolFileSpec(),
4055                                               0, 0, symfile_module_specs)) {
4056         // Now extract the module spec that matches the target architecture
4057         ModuleSpec target_arch_module_spec;
4058         ModuleSpec symfile_module_spec;
4059         target_arch_module_spec.GetArchitecture() = target->GetArchitecture();
4060         if (symfile_module_specs.FindMatchingModuleSpec(target_arch_module_spec,
4061                                                         symfile_module_spec)) {
4062           // See if it has a UUID?
4063           if (symfile_module_spec.GetUUID().IsValid()) {
4064             // It has a UUID, look for this UUID in the target modules
4065             ModuleSpec symfile_uuid_module_spec;
4066             symfile_uuid_module_spec.GetUUID() = symfile_module_spec.GetUUID();
4067             target->GetImages().FindModules(symfile_uuid_module_spec,
4068                                             matching_module_list);
4069             num_matches = matching_module_list.GetSize();
4070           }
4071         }
4072 
4073         if (num_matches == 0) {
4074           // No matches yet, iterate through the module specs to find a UUID
4075           // value that we can match up to an image in our target
4076           const size_t num_symfile_module_specs =
4077               symfile_module_specs.GetSize();
4078           for (size_t i = 0; i < num_symfile_module_specs && num_matches == 0;
4079                ++i) {
4080             if (symfile_module_specs.GetModuleSpecAtIndex(
4081                     i, symfile_module_spec)) {
4082               if (symfile_module_spec.GetUUID().IsValid()) {
4083                 // It has a UUID, look for this UUID in the target modules
4084                 ModuleSpec symfile_uuid_module_spec;
4085                 symfile_uuid_module_spec.GetUUID() =
4086                     symfile_module_spec.GetUUID();
4087                 target->GetImages().FindModules(symfile_uuid_module_spec,
4088                                                 matching_module_list);
4089                 num_matches = matching_module_list.GetSize();
4090               }
4091             }
4092           }
4093         }
4094       }
4095 
4096       // Just try to match up the file by basename if we have no matches at
4097       // this point
4098       if (num_matches == 0) {
4099         target->GetImages().FindModules(module_spec, matching_module_list);
4100         num_matches = matching_module_list.GetSize();
4101       }
4102 
4103       while (num_matches == 0) {
4104         ConstString filename_no_extension(
4105             module_spec.GetFileSpec().GetFileNameStrippingExtension());
4106         // Empty string returned, lets bail
4107         if (!filename_no_extension)
4108           break;
4109 
4110         // Check if there was no extension to strip and the basename is the
4111         // same
4112         if (filename_no_extension == module_spec.GetFileSpec().GetFilename())
4113           break;
4114 
4115         // Replace basename with one less extension
4116         module_spec.GetFileSpec().GetFilename() = filename_no_extension;
4117 
4118         target->GetImages().FindModules(module_spec, matching_module_list);
4119         num_matches = matching_module_list.GetSize();
4120       }
4121 
4122       if (num_matches > 1) {
4123         result.AppendErrorWithFormat("multiple modules match symbol file '%s', "
4124                                      "use the --uuid option to resolve the "
4125                                      "ambiguity.\n",
4126                                      symfile_path);
4127       } else if (num_matches == 1) {
4128         ModuleSP module_sp(matching_module_list.GetModuleAtIndex(0));
4129 
4130         // The module has not yet created its symbol vendor, we can just give
4131         // the existing target module the symfile path to use for when it
4132         // decides to create it!
4133         module_sp->SetSymbolFileFileSpec(symbol_fspec);
4134 
4135         SymbolFile *symbol_file =
4136             module_sp->GetSymbolFile(true, &result.GetErrorStream());
4137         if (symbol_file) {
4138           ObjectFile *object_file = symbol_file->GetObjectFile();
4139 
4140           if (object_file && object_file->GetFileSpec() == symbol_fspec) {
4141             // Provide feedback that the symfile has been successfully added.
4142             const FileSpec &module_fs = module_sp->GetFileSpec();
4143             result.AppendMessageWithFormat(
4144                 "symbol file '%s' has been added to '%s'\n", symfile_path,
4145                 module_fs.GetPath().c_str());
4146 
4147             // Let clients know something changed in the module if it is
4148             // currently loaded
4149             ModuleList module_list;
4150             module_list.Append(module_sp);
4151             target->SymbolsDidLoad(module_list);
4152 
4153             // Make sure we load any scripting resources that may be embedded
4154             // in the debug info files in case the platform supports that.
4155             Status error;
4156             StreamString feedback_stream;
4157             module_sp->LoadScriptingResourceInTarget(target, error,
4158                                                      &feedback_stream);
4159             if (error.Fail() && error.AsCString())
4160               result.AppendWarningWithFormat(
4161                   "unable to load scripting data for module %s - error "
4162                   "reported was %s",
4163                   module_sp->GetFileSpec()
4164                       .GetFileNameStrippingExtension()
4165                       .GetCString(),
4166                   error.AsCString());
4167             else if (feedback_stream.GetSize())
4168               result.AppendWarningWithFormat("%s", feedback_stream.GetData());
4169 
4170             flush = true;
4171             result.SetStatus(eReturnStatusSuccessFinishResult);
4172             return true;
4173           }
4174         }
4175         // Clear the symbol file spec if anything went wrong
4176         module_sp->SetSymbolFileFileSpec(FileSpec());
4177       }
4178 
4179       namespace fs = llvm::sys::fs;
4180       if (module_spec.GetUUID().IsValid()) {
4181         StreamString ss_symfile_uuid;
4182         module_spec.GetUUID().Dump(&ss_symfile_uuid);
4183         result.AppendErrorWithFormat(
4184             "symbol file '%s' (%s) does not match any existing module%s\n",
4185             symfile_path, ss_symfile_uuid.GetData(),
4186             !fs::is_regular_file(symbol_fspec.GetPath())
4187                 ? "\n       please specify the full path to the symbol file"
4188                 : "");
4189       } else {
4190         result.AppendErrorWithFormat(
4191             "symbol file '%s' does not match any existing module%s\n",
4192             symfile_path,
4193             !fs::is_regular_file(symbol_fspec.GetPath())
4194                 ? "\n       please specify the full path to the symbol file"
4195                 : "");
4196       }
4197     } else {
4198       result.AppendError(
4199           "one or more executable image paths must be specified");
4200     }
4201     result.SetStatus(eReturnStatusFailed);
4202     return false;
4203   }
4204 
4205   bool DoExecute(Args &args, CommandReturnObject &result) override {
4206     Target *target = m_exe_ctx.GetTargetPtr();
4207     result.SetStatus(eReturnStatusFailed);
4208     bool flush = false;
4209     ModuleSpec module_spec;
4210     const bool uuid_option_set =
4211         m_uuid_option_group.GetOptionValue().OptionWasSet();
4212     const bool file_option_set = m_file_option.GetOptionValue().OptionWasSet();
4213     const bool frame_option_set =
4214         m_current_frame_option.GetOptionValue().OptionWasSet();
4215     const size_t argc = args.GetArgumentCount();
4216 
4217     if (argc == 0) {
4218       if (uuid_option_set || file_option_set || frame_option_set) {
4219         bool success = false;
4220         bool error_set = false;
4221         if (frame_option_set) {
4222           Process *process = m_exe_ctx.GetProcessPtr();
4223           if (process) {
4224             const StateType process_state = process->GetState();
4225             if (StateIsStoppedState(process_state, true)) {
4226               StackFrame *frame = m_exe_ctx.GetFramePtr();
4227               if (frame) {
4228                 ModuleSP frame_module_sp(
4229                     frame->GetSymbolContext(eSymbolContextModule).module_sp);
4230                 if (frame_module_sp) {
4231                   if (FileSystem::Instance().Exists(
4232                           frame_module_sp->GetPlatformFileSpec())) {
4233                     module_spec.GetArchitecture() =
4234                         frame_module_sp->GetArchitecture();
4235                     module_spec.GetFileSpec() =
4236                         frame_module_sp->GetPlatformFileSpec();
4237                   }
4238                   module_spec.GetUUID() = frame_module_sp->GetUUID();
4239                   success = module_spec.GetUUID().IsValid() ||
4240                             module_spec.GetFileSpec();
4241                 } else {
4242                   result.AppendError("frame has no module");
4243                   error_set = true;
4244                 }
4245               } else {
4246                 result.AppendError("invalid current frame");
4247                 error_set = true;
4248               }
4249             } else {
4250               result.AppendErrorWithFormat("process is not stopped: %s",
4251                                            StateAsCString(process_state));
4252               error_set = true;
4253             }
4254           } else {
4255             result.AppendError(
4256                 "a process must exist in order to use the --frame option");
4257             error_set = true;
4258           }
4259         } else {
4260           if (uuid_option_set) {
4261             module_spec.GetUUID() =
4262                 m_uuid_option_group.GetOptionValue().GetCurrentValue();
4263             success |= module_spec.GetUUID().IsValid();
4264           } else if (file_option_set) {
4265             module_spec.GetFileSpec() =
4266                 m_file_option.GetOptionValue().GetCurrentValue();
4267             ModuleSP module_sp(
4268                 target->GetImages().FindFirstModule(module_spec));
4269             if (module_sp) {
4270               module_spec.GetFileSpec() = module_sp->GetFileSpec();
4271               module_spec.GetPlatformFileSpec() =
4272                   module_sp->GetPlatformFileSpec();
4273               module_spec.GetUUID() = module_sp->GetUUID();
4274               module_spec.GetArchitecture() = module_sp->GetArchitecture();
4275             } else {
4276               module_spec.GetArchitecture() = target->GetArchitecture();
4277             }
4278             success |= module_spec.GetUUID().IsValid() ||
4279                        FileSystem::Instance().Exists(module_spec.GetFileSpec());
4280           }
4281         }
4282 
4283         if (success) {
4284           if (Symbols::DownloadObjectAndSymbolFile(module_spec)) {
4285             if (module_spec.GetSymbolFileSpec())
4286               success = AddModuleSymbols(target, module_spec, flush, result);
4287           }
4288         }
4289 
4290         if (!success && !error_set) {
4291           StreamString error_strm;
4292           if (uuid_option_set) {
4293             error_strm.PutCString("unable to find debug symbols for UUID ");
4294             module_spec.GetUUID().Dump(&error_strm);
4295           } else if (file_option_set) {
4296             error_strm.PutCString(
4297                 "unable to find debug symbols for the executable file ");
4298             error_strm << module_spec.GetFileSpec();
4299           } else if (frame_option_set) {
4300             error_strm.PutCString(
4301                 "unable to find debug symbols for the current frame");
4302           }
4303           result.AppendError(error_strm.GetString());
4304         }
4305       } else {
4306         result.AppendError("one or more symbol file paths must be specified, "
4307                            "or options must be specified");
4308       }
4309     } else {
4310       if (uuid_option_set) {
4311         result.AppendError("specify either one or more paths to symbol files "
4312                            "or use the --uuid option without arguments");
4313       } else if (frame_option_set) {
4314         result.AppendError("specify either one or more paths to symbol files "
4315                            "or use the --frame option without arguments");
4316       } else if (file_option_set && argc > 1) {
4317         result.AppendError("specify at most one symbol file path when "
4318                            "--shlib option is set");
4319       } else {
4320         PlatformSP platform_sp(target->GetPlatform());
4321 
4322         for (auto &entry : args.entries()) {
4323           if (!entry.ref().empty()) {
4324             auto &symbol_file_spec = module_spec.GetSymbolFileSpec();
4325             symbol_file_spec.SetFile(entry.ref(), FileSpec::Style::native);
4326             FileSystem::Instance().Resolve(symbol_file_spec);
4327             if (file_option_set) {
4328               module_spec.GetFileSpec() =
4329                   m_file_option.GetOptionValue().GetCurrentValue();
4330             }
4331             if (platform_sp) {
4332               FileSpec symfile_spec;
4333               if (platform_sp
4334                       ->ResolveSymbolFile(*target, module_spec, symfile_spec)
4335                       .Success())
4336                 module_spec.GetSymbolFileSpec() = symfile_spec;
4337             }
4338 
4339             ArchSpec arch;
4340             bool symfile_exists =
4341                 FileSystem::Instance().Exists(module_spec.GetSymbolFileSpec());
4342 
4343             if (symfile_exists) {
4344               if (!AddModuleSymbols(target, module_spec, flush, result))
4345                 break;
4346             } else {
4347               std::string resolved_symfile_path =
4348                   module_spec.GetSymbolFileSpec().GetPath();
4349               if (resolved_symfile_path != entry.ref()) {
4350                 result.AppendErrorWithFormat(
4351                     "invalid module path '%s' with resolved path '%s'\n",
4352                     entry.c_str(), resolved_symfile_path.c_str());
4353                 break;
4354               }
4355               result.AppendErrorWithFormat("invalid module path '%s'\n",
4356                                            entry.c_str());
4357               break;
4358             }
4359           }
4360         }
4361       }
4362     }
4363 
4364     if (flush) {
4365       Process *process = m_exe_ctx.GetProcessPtr();
4366       if (process)
4367         process->Flush();
4368     }
4369     return result.Succeeded();
4370   }
4371 
4372   OptionGroupOptions m_option_group;
4373   OptionGroupUUID m_uuid_option_group;
4374   OptionGroupFile m_file_option;
4375   OptionGroupBoolean m_current_frame_option;
4376 };
4377 
4378 #pragma mark CommandObjectTargetSymbols
4379 
4380 // CommandObjectTargetSymbols
4381 
4382 class CommandObjectTargetSymbols : public CommandObjectMultiword {
4383 public:
4384   // Constructors and Destructors
4385   CommandObjectTargetSymbols(CommandInterpreter &interpreter)
4386       : CommandObjectMultiword(
4387             interpreter, "target symbols",
4388             "Commands for adding and managing debug symbol files.",
4389             "target symbols <sub-command> ...") {
4390     LoadSubCommand(
4391         "add", CommandObjectSP(new CommandObjectTargetSymbolsAdd(interpreter)));
4392   }
4393 
4394   ~CommandObjectTargetSymbols() override = default;
4395 
4396 private:
4397   // For CommandObjectTargetModules only
4398   DISALLOW_COPY_AND_ASSIGN(CommandObjectTargetSymbols);
4399 };
4400 
4401 #pragma mark CommandObjectTargetStopHookAdd
4402 
4403 // CommandObjectTargetStopHookAdd
4404 #define LLDB_OPTIONS_target_stop_hook_add
4405 #include "CommandOptions.inc"
4406 
4407 class CommandObjectTargetStopHookAdd : public CommandObjectParsed,
4408                                        public IOHandlerDelegateMultiline {
4409 public:
4410   class CommandOptions : public Options {
4411   public:
4412     CommandOptions()
4413         : Options(), m_line_start(0), m_line_end(UINT_MAX),
4414           m_func_name_type_mask(eFunctionNameTypeAuto),
4415           m_sym_ctx_specified(false), m_thread_specified(false),
4416           m_use_one_liner(false), m_one_liner() {}
4417 
4418     ~CommandOptions() override = default;
4419 
4420     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
4421       return llvm::makeArrayRef(g_target_stop_hook_add_options);
4422     }
4423 
4424     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
4425                           ExecutionContext *execution_context) override {
4426       Status error;
4427       const int short_option = m_getopt_table[option_idx].val;
4428 
4429       switch (short_option) {
4430       case 'c':
4431         m_class_name = option_arg;
4432         m_sym_ctx_specified = true;
4433         break;
4434 
4435       case 'e':
4436         if (option_arg.getAsInteger(0, m_line_end)) {
4437           error.SetErrorStringWithFormat("invalid end line number: \"%s\"",
4438                                          option_arg.str().c_str());
4439           break;
4440         }
4441         m_sym_ctx_specified = true;
4442         break;
4443 
4444       case 'G': {
4445         bool value, success;
4446         value = OptionArgParser::ToBoolean(option_arg, false, &success);
4447         if (success) {
4448           m_auto_continue = value;
4449         } else
4450           error.SetErrorStringWithFormat(
4451               "invalid boolean value '%s' passed for -G option",
4452               option_arg.str().c_str());
4453       }
4454       break;
4455       case 'l':
4456         if (option_arg.getAsInteger(0, m_line_start)) {
4457           error.SetErrorStringWithFormat("invalid start line number: \"%s\"",
4458                                          option_arg.str().c_str());
4459           break;
4460         }
4461         m_sym_ctx_specified = true;
4462         break;
4463 
4464       case 'i':
4465         m_no_inlines = true;
4466         break;
4467 
4468       case 'n':
4469         m_function_name = option_arg;
4470         m_func_name_type_mask |= eFunctionNameTypeAuto;
4471         m_sym_ctx_specified = true;
4472         break;
4473 
4474       case 'f':
4475         m_file_name = option_arg;
4476         m_sym_ctx_specified = true;
4477         break;
4478 
4479       case 's':
4480         m_module_name = option_arg;
4481         m_sym_ctx_specified = true;
4482         break;
4483 
4484       case 't':
4485         if (option_arg.getAsInteger(0, m_thread_id))
4486           error.SetErrorStringWithFormat("invalid thread id string '%s'",
4487                                          option_arg.str().c_str());
4488         m_thread_specified = true;
4489         break;
4490 
4491       case 'T':
4492         m_thread_name = option_arg;
4493         m_thread_specified = true;
4494         break;
4495 
4496       case 'q':
4497         m_queue_name = option_arg;
4498         m_thread_specified = true;
4499         break;
4500 
4501       case 'x':
4502         if (option_arg.getAsInteger(0, m_thread_index))
4503           error.SetErrorStringWithFormat("invalid thread index string '%s'",
4504                                          option_arg.str().c_str());
4505         m_thread_specified = true;
4506         break;
4507 
4508       case 'o':
4509         m_use_one_liner = true;
4510         m_one_liner.push_back(option_arg);
4511         break;
4512 
4513       default:
4514         llvm_unreachable("Unimplemented option");
4515       }
4516       return error;
4517     }
4518 
4519     void OptionParsingStarting(ExecutionContext *execution_context) override {
4520       m_class_name.clear();
4521       m_function_name.clear();
4522       m_line_start = 0;
4523       m_line_end = UINT_MAX;
4524       m_file_name.clear();
4525       m_module_name.clear();
4526       m_func_name_type_mask = eFunctionNameTypeAuto;
4527       m_thread_id = LLDB_INVALID_THREAD_ID;
4528       m_thread_index = UINT32_MAX;
4529       m_thread_name.clear();
4530       m_queue_name.clear();
4531 
4532       m_no_inlines = false;
4533       m_sym_ctx_specified = false;
4534       m_thread_specified = false;
4535 
4536       m_use_one_liner = false;
4537       m_one_liner.clear();
4538       m_auto_continue = false;
4539     }
4540 
4541     std::string m_class_name;
4542     std::string m_function_name;
4543     uint32_t m_line_start;
4544     uint32_t m_line_end;
4545     std::string m_file_name;
4546     std::string m_module_name;
4547     uint32_t m_func_name_type_mask; // A pick from lldb::FunctionNameType.
4548     lldb::tid_t m_thread_id;
4549     uint32_t m_thread_index;
4550     std::string m_thread_name;
4551     std::string m_queue_name;
4552     bool m_sym_ctx_specified;
4553     bool m_no_inlines;
4554     bool m_thread_specified;
4555     // Instance variables to hold the values for one_liner options.
4556     bool m_use_one_liner;
4557     std::vector<std::string> m_one_liner;
4558     bool m_auto_continue;
4559   };
4560 
4561   CommandObjectTargetStopHookAdd(CommandInterpreter &interpreter)
4562       : CommandObjectParsed(interpreter, "target stop-hook add",
4563                             "Add a hook to be executed when the target stops.",
4564                             "target stop-hook add"),
4565         IOHandlerDelegateMultiline("DONE",
4566                                    IOHandlerDelegate::Completion::LLDBCommand),
4567         m_options() {}
4568 
4569   ~CommandObjectTargetStopHookAdd() override = default;
4570 
4571   Options *GetOptions() override { return &m_options; }
4572 
4573 protected:
4574   void IOHandlerActivated(IOHandler &io_handler, bool interactive) override {
4575     StreamFileSP output_sp(io_handler.GetOutputStreamFileSP());
4576     if (output_sp && interactive) {
4577       output_sp->PutCString(
4578           "Enter your stop hook command(s).  Type 'DONE' to end.\n");
4579       output_sp->Flush();
4580     }
4581   }
4582 
4583   void IOHandlerInputComplete(IOHandler &io_handler,
4584                               std::string &line) override {
4585     if (m_stop_hook_sp) {
4586       if (line.empty()) {
4587         StreamFileSP error_sp(io_handler.GetErrorStreamFileSP());
4588         if (error_sp) {
4589           error_sp->Printf("error: stop hook #%" PRIu64
4590                            " aborted, no commands.\n",
4591                            m_stop_hook_sp->GetID());
4592           error_sp->Flush();
4593         }
4594         Target *target = GetDebugger().GetSelectedTarget().get();
4595         if (target)
4596           target->RemoveStopHookByID(m_stop_hook_sp->GetID());
4597       } else {
4598         m_stop_hook_sp->GetCommandPointer()->SplitIntoLines(line);
4599         StreamFileSP output_sp(io_handler.GetOutputStreamFileSP());
4600         if (output_sp) {
4601           output_sp->Printf("Stop hook #%" PRIu64 " added.\n",
4602                             m_stop_hook_sp->GetID());
4603           output_sp->Flush();
4604         }
4605       }
4606       m_stop_hook_sp.reset();
4607     }
4608     io_handler.SetIsDone(true);
4609   }
4610 
4611   bool DoExecute(Args &command, CommandReturnObject &result) override {
4612     m_stop_hook_sp.reset();
4613 
4614     Target &target = GetSelectedOrDummyTarget();
4615     Target::StopHookSP new_hook_sp = target.CreateStopHook();
4616 
4617     //  First step, make the specifier.
4618     std::unique_ptr<SymbolContextSpecifier> specifier_up;
4619     if (m_options.m_sym_ctx_specified) {
4620       specifier_up.reset(
4621           new SymbolContextSpecifier(GetDebugger().GetSelectedTarget()));
4622 
4623       if (!m_options.m_module_name.empty()) {
4624         specifier_up->AddSpecification(
4625             m_options.m_module_name.c_str(),
4626             SymbolContextSpecifier::eModuleSpecified);
4627       }
4628 
4629       if (!m_options.m_class_name.empty()) {
4630         specifier_up->AddSpecification(
4631             m_options.m_class_name.c_str(),
4632             SymbolContextSpecifier::eClassOrNamespaceSpecified);
4633       }
4634 
4635       if (!m_options.m_file_name.empty()) {
4636         specifier_up->AddSpecification(m_options.m_file_name.c_str(),
4637                                        SymbolContextSpecifier::eFileSpecified);
4638       }
4639 
4640       if (m_options.m_line_start != 0) {
4641         specifier_up->AddLineSpecification(
4642             m_options.m_line_start,
4643             SymbolContextSpecifier::eLineStartSpecified);
4644       }
4645 
4646       if (m_options.m_line_end != UINT_MAX) {
4647         specifier_up->AddLineSpecification(
4648             m_options.m_line_end, SymbolContextSpecifier::eLineEndSpecified);
4649       }
4650 
4651       if (!m_options.m_function_name.empty()) {
4652         specifier_up->AddSpecification(
4653             m_options.m_function_name.c_str(),
4654             SymbolContextSpecifier::eFunctionSpecified);
4655       }
4656     }
4657 
4658       if (specifier_up)
4659         new_hook_sp->SetSpecifier(specifier_up.release());
4660 
4661       // Next see if any of the thread options have been entered:
4662 
4663       if (m_options.m_thread_specified) {
4664         ThreadSpec *thread_spec = new ThreadSpec();
4665 
4666         if (m_options.m_thread_id != LLDB_INVALID_THREAD_ID) {
4667           thread_spec->SetTID(m_options.m_thread_id);
4668         }
4669 
4670         if (m_options.m_thread_index != UINT32_MAX)
4671           thread_spec->SetIndex(m_options.m_thread_index);
4672 
4673         if (!m_options.m_thread_name.empty())
4674           thread_spec->SetName(m_options.m_thread_name.c_str());
4675 
4676         if (!m_options.m_queue_name.empty())
4677           thread_spec->SetQueueName(m_options.m_queue_name.c_str());
4678 
4679         new_hook_sp->SetThreadSpecifier(thread_spec);
4680       }
4681 
4682       new_hook_sp->SetAutoContinue(m_options.m_auto_continue);
4683       if (m_options.m_use_one_liner) {
4684         // Use one-liners.
4685         for (auto cmd : m_options.m_one_liner)
4686           new_hook_sp->GetCommandPointer()->AppendString(
4687             cmd.c_str());
4688         result.AppendMessageWithFormat("Stop hook #%" PRIu64 " added.\n",
4689                                        new_hook_sp->GetID());
4690       } else {
4691         m_stop_hook_sp = new_hook_sp;
4692         m_interpreter.GetLLDBCommandsFromIOHandler(
4693             "> ",     // Prompt
4694             *this,    // IOHandlerDelegate
4695             true,     // Run IOHandler in async mode
4696             nullptr); // Baton for the "io_handler" that will be passed back
4697                       // into our IOHandlerDelegate functions
4698       }
4699       result.SetStatus(eReturnStatusSuccessFinishNoResult);
4700 
4701     return result.Succeeded();
4702   }
4703 
4704 private:
4705   CommandOptions m_options;
4706   Target::StopHookSP m_stop_hook_sp;
4707 };
4708 
4709 #pragma mark CommandObjectTargetStopHookDelete
4710 
4711 // CommandObjectTargetStopHookDelete
4712 
4713 class CommandObjectTargetStopHookDelete : public CommandObjectParsed {
4714 public:
4715   CommandObjectTargetStopHookDelete(CommandInterpreter &interpreter)
4716       : CommandObjectParsed(interpreter, "target stop-hook delete",
4717                             "Delete a stop-hook.",
4718                             "target stop-hook delete [<idx>]") {}
4719 
4720   ~CommandObjectTargetStopHookDelete() override = default;
4721 
4722 protected:
4723   bool DoExecute(Args &command, CommandReturnObject &result) override {
4724     Target &target = GetSelectedOrDummyTarget();
4725     // FIXME: see if we can use the breakpoint id style parser?
4726     size_t num_args = command.GetArgumentCount();
4727     if (num_args == 0) {
4728       if (!m_interpreter.Confirm("Delete all stop hooks?", true)) {
4729         result.SetStatus(eReturnStatusFailed);
4730         return false;
4731       } else {
4732         target.RemoveAllStopHooks();
4733       }
4734     } else {
4735       bool success;
4736       for (size_t i = 0; i < num_args; i++) {
4737         lldb::user_id_t user_id = StringConvert::ToUInt32(
4738             command.GetArgumentAtIndex(i), 0, 0, &success);
4739         if (!success) {
4740           result.AppendErrorWithFormat("invalid stop hook id: \"%s\".\n",
4741                                        command.GetArgumentAtIndex(i));
4742           result.SetStatus(eReturnStatusFailed);
4743           return false;
4744         }
4745         success = target.RemoveStopHookByID(user_id);
4746         if (!success) {
4747           result.AppendErrorWithFormat("unknown stop hook id: \"%s\".\n",
4748                                        command.GetArgumentAtIndex(i));
4749           result.SetStatus(eReturnStatusFailed);
4750           return false;
4751         }
4752       }
4753     }
4754       result.SetStatus(eReturnStatusSuccessFinishNoResult);
4755     return result.Succeeded();
4756   }
4757 };
4758 
4759 #pragma mark CommandObjectTargetStopHookEnableDisable
4760 
4761 // CommandObjectTargetStopHookEnableDisable
4762 
4763 class CommandObjectTargetStopHookEnableDisable : public CommandObjectParsed {
4764 public:
4765   CommandObjectTargetStopHookEnableDisable(CommandInterpreter &interpreter,
4766                                            bool enable, const char *name,
4767                                            const char *help, const char *syntax)
4768       : CommandObjectParsed(interpreter, name, help, syntax), m_enable(enable) {
4769   }
4770 
4771   ~CommandObjectTargetStopHookEnableDisable() override = default;
4772 
4773 protected:
4774   bool DoExecute(Args &command, CommandReturnObject &result) override {
4775     Target &target = GetSelectedOrDummyTarget();
4776     // FIXME: see if we can use the breakpoint id style parser?
4777     size_t num_args = command.GetArgumentCount();
4778     bool success;
4779 
4780     if (num_args == 0) {
4781       target.SetAllStopHooksActiveState(m_enable);
4782     } else {
4783       for (size_t i = 0; i < num_args; i++) {
4784         lldb::user_id_t user_id = StringConvert::ToUInt32(
4785             command.GetArgumentAtIndex(i), 0, 0, &success);
4786         if (!success) {
4787           result.AppendErrorWithFormat("invalid stop hook id: \"%s\".\n",
4788                                        command.GetArgumentAtIndex(i));
4789           result.SetStatus(eReturnStatusFailed);
4790           return false;
4791         }
4792         success = target.SetStopHookActiveStateByID(user_id, m_enable);
4793         if (!success) {
4794           result.AppendErrorWithFormat("unknown stop hook id: \"%s\".\n",
4795                                        command.GetArgumentAtIndex(i));
4796           result.SetStatus(eReturnStatusFailed);
4797           return false;
4798         }
4799       }
4800     }
4801       result.SetStatus(eReturnStatusSuccessFinishNoResult);
4802     return result.Succeeded();
4803   }
4804 
4805 private:
4806   bool m_enable;
4807 };
4808 
4809 #pragma mark CommandObjectTargetStopHookList
4810 
4811 // CommandObjectTargetStopHookList
4812 
4813 class CommandObjectTargetStopHookList : public CommandObjectParsed {
4814 public:
4815   CommandObjectTargetStopHookList(CommandInterpreter &interpreter)
4816       : CommandObjectParsed(interpreter, "target stop-hook list",
4817                             "List all stop-hooks.",
4818                             "target stop-hook list [<type>]") {}
4819 
4820   ~CommandObjectTargetStopHookList() override = default;
4821 
4822 protected:
4823   bool DoExecute(Args &command, CommandReturnObject &result) override {
4824     Target &target = GetSelectedOrDummyTarget();
4825 
4826     size_t num_hooks = target.GetNumStopHooks();
4827     if (num_hooks == 0) {
4828       result.GetOutputStream().PutCString("No stop hooks.\n");
4829     } else {
4830       for (size_t i = 0; i < num_hooks; i++) {
4831         Target::StopHookSP this_hook = target.GetStopHookAtIndex(i);
4832         if (i > 0)
4833           result.GetOutputStream().PutCString("\n");
4834         this_hook->GetDescription(&(result.GetOutputStream()),
4835                                   eDescriptionLevelFull);
4836       }
4837     }
4838     result.SetStatus(eReturnStatusSuccessFinishResult);
4839     return result.Succeeded();
4840   }
4841 };
4842 
4843 #pragma mark CommandObjectMultiwordTargetStopHooks
4844 
4845 // CommandObjectMultiwordTargetStopHooks
4846 
4847 class CommandObjectMultiwordTargetStopHooks : public CommandObjectMultiword {
4848 public:
4849   CommandObjectMultiwordTargetStopHooks(CommandInterpreter &interpreter)
4850       : CommandObjectMultiword(
4851             interpreter, "target stop-hook",
4852             "Commands for operating on debugger target stop-hooks.",
4853             "target stop-hook <subcommand> [<subcommand-options>]") {
4854     LoadSubCommand("add", CommandObjectSP(
4855                               new CommandObjectTargetStopHookAdd(interpreter)));
4856     LoadSubCommand(
4857         "delete",
4858         CommandObjectSP(new CommandObjectTargetStopHookDelete(interpreter)));
4859     LoadSubCommand("disable",
4860                    CommandObjectSP(new CommandObjectTargetStopHookEnableDisable(
4861                        interpreter, false, "target stop-hook disable [<id>]",
4862                        "Disable a stop-hook.", "target stop-hook disable")));
4863     LoadSubCommand("enable",
4864                    CommandObjectSP(new CommandObjectTargetStopHookEnableDisable(
4865                        interpreter, true, "target stop-hook enable [<id>]",
4866                        "Enable a stop-hook.", "target stop-hook enable")));
4867     LoadSubCommand("list", CommandObjectSP(new CommandObjectTargetStopHookList(
4868                                interpreter)));
4869   }
4870 
4871   ~CommandObjectMultiwordTargetStopHooks() override = default;
4872 };
4873 
4874 #pragma mark CommandObjectMultiwordTarget
4875 
4876 // CommandObjectMultiwordTarget
4877 
4878 CommandObjectMultiwordTarget::CommandObjectMultiwordTarget(
4879     CommandInterpreter &interpreter)
4880     : CommandObjectMultiword(interpreter, "target",
4881                              "Commands for operating on debugger targets.",
4882                              "target <subcommand> [<subcommand-options>]") {
4883   LoadSubCommand("create",
4884                  CommandObjectSP(new CommandObjectTargetCreate(interpreter)));
4885   LoadSubCommand("delete",
4886                  CommandObjectSP(new CommandObjectTargetDelete(interpreter)));
4887   LoadSubCommand("list",
4888                  CommandObjectSP(new CommandObjectTargetList(interpreter)));
4889   LoadSubCommand("select",
4890                  CommandObjectSP(new CommandObjectTargetSelect(interpreter)));
4891   LoadSubCommand(
4892       "stop-hook",
4893       CommandObjectSP(new CommandObjectMultiwordTargetStopHooks(interpreter)));
4894   LoadSubCommand("modules",
4895                  CommandObjectSP(new CommandObjectTargetModules(interpreter)));
4896   LoadSubCommand("symbols",
4897                  CommandObjectSP(new CommandObjectTargetSymbols(interpreter)));
4898   LoadSubCommand("variable",
4899                  CommandObjectSP(new CommandObjectTargetVariable(interpreter)));
4900 }
4901 
4902 CommandObjectMultiwordTarget::~CommandObjectMultiwordTarget() = default;
4903