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