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