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