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