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 ehframe_sp =
3449           func_unwinders_sp->GetEHFrameUnwindPlan(*target);
3450       if (ehframe_sp) {
3451         result.GetOutputStream().Printf("eh_frame UnwindPlan:\n");
3452         ehframe_sp->Dump(result.GetOutputStream(), thread.get(),
3453                          LLDB_INVALID_ADDRESS);
3454         result.GetOutputStream().Printf("\n");
3455       }
3456 
3457       UnwindPlanSP ehframe_augmented_sp =
3458           func_unwinders_sp->GetEHFrameAugmentedUnwindPlan(*target, *thread);
3459       if (ehframe_augmented_sp) {
3460         result.GetOutputStream().Printf("eh_frame augmented UnwindPlan:\n");
3461         ehframe_augmented_sp->Dump(result.GetOutputStream(), thread.get(),
3462                                    LLDB_INVALID_ADDRESS);
3463         result.GetOutputStream().Printf("\n");
3464       }
3465 
3466       if (UnwindPlanSP plan_sp =
3467               func_unwinders_sp->GetDebugFrameUnwindPlan(*target)) {
3468         result.GetOutputStream().Printf("debug_frame UnwindPlan:\n");
3469         plan_sp->Dump(result.GetOutputStream(), thread.get(),
3470                       LLDB_INVALID_ADDRESS);
3471         result.GetOutputStream().Printf("\n");
3472       }
3473 
3474       if (UnwindPlanSP plan_sp =
3475               func_unwinders_sp->GetDebugFrameAugmentedUnwindPlan(*target,
3476                                                                   *thread)) {
3477         result.GetOutputStream().Printf("debug_frame augmented UnwindPlan:\n");
3478         plan_sp->Dump(result.GetOutputStream(), thread.get(),
3479                       LLDB_INVALID_ADDRESS);
3480         result.GetOutputStream().Printf("\n");
3481       }
3482 
3483       UnwindPlanSP arm_unwind_sp =
3484           func_unwinders_sp->GetArmUnwindUnwindPlan(*target);
3485       if (arm_unwind_sp) {
3486         result.GetOutputStream().Printf("ARM.exidx unwind UnwindPlan:\n");
3487         arm_unwind_sp->Dump(result.GetOutputStream(), thread.get(),
3488                             LLDB_INVALID_ADDRESS);
3489         result.GetOutputStream().Printf("\n");
3490       }
3491 
3492       if (UnwindPlanSP symfile_plan_sp =
3493               func_unwinders_sp->GetSymbolFileUnwindPlan(*thread)) {
3494         result.GetOutputStream().Printf("Symbol file UnwindPlan:\n");
3495         symfile_plan_sp->Dump(result.GetOutputStream(), thread.get(),
3496                               LLDB_INVALID_ADDRESS);
3497         result.GetOutputStream().Printf("\n");
3498       }
3499 
3500       UnwindPlanSP compact_unwind_sp =
3501           func_unwinders_sp->GetCompactUnwindUnwindPlan(*target);
3502       if (compact_unwind_sp) {
3503         result.GetOutputStream().Printf("Compact unwind UnwindPlan:\n");
3504         compact_unwind_sp->Dump(result.GetOutputStream(), thread.get(),
3505                                 LLDB_INVALID_ADDRESS);
3506         result.GetOutputStream().Printf("\n");
3507       }
3508 
3509       if (fast_unwind_plan) {
3510         result.GetOutputStream().Printf("Fast UnwindPlan:\n");
3511         fast_unwind_plan->Dump(result.GetOutputStream(), thread.get(),
3512                                LLDB_INVALID_ADDRESS);
3513         result.GetOutputStream().Printf("\n");
3514       }
3515 
3516       ABISP abi_sp = process->GetABI();
3517       if (abi_sp) {
3518         UnwindPlan arch_default(lldb::eRegisterKindGeneric);
3519         if (abi_sp->CreateDefaultUnwindPlan(arch_default)) {
3520           result.GetOutputStream().Printf("Arch default UnwindPlan:\n");
3521           arch_default.Dump(result.GetOutputStream(), thread.get(),
3522                             LLDB_INVALID_ADDRESS);
3523           result.GetOutputStream().Printf("\n");
3524         }
3525 
3526         UnwindPlan arch_entry(lldb::eRegisterKindGeneric);
3527         if (abi_sp->CreateFunctionEntryUnwindPlan(arch_entry)) {
3528           result.GetOutputStream().Printf(
3529               "Arch default at entry point UnwindPlan:\n");
3530           arch_entry.Dump(result.GetOutputStream(), thread.get(),
3531                           LLDB_INVALID_ADDRESS);
3532           result.GetOutputStream().Printf("\n");
3533         }
3534       }
3535 
3536       result.GetOutputStream().Printf("\n");
3537     }
3538     return result.Succeeded();
3539   }
3540 
3541   CommandOptions m_options;
3542 };
3543 
3544 // Lookup information in images
3545 #define LLDB_OPTIONS_target_modules_lookup
3546 #include "CommandOptions.inc"
3547 
3548 class CommandObjectTargetModulesLookup : public CommandObjectParsed {
3549 public:
3550   enum {
3551     eLookupTypeInvalid = -1,
3552     eLookupTypeAddress = 0,
3553     eLookupTypeSymbol,
3554     eLookupTypeFileLine, // Line is optional
3555     eLookupTypeFunction,
3556     eLookupTypeFunctionOrSymbol,
3557     eLookupTypeType,
3558     kNumLookupTypes
3559   };
3560 
3561   class CommandOptions : public Options {
3562   public:
3563     CommandOptions() : Options() { OptionParsingStarting(nullptr); }
3564 
3565     ~CommandOptions() override = default;
3566 
3567     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
3568                           ExecutionContext *execution_context) override {
3569       Status error;
3570 
3571       const int short_option = m_getopt_table[option_idx].val;
3572 
3573       switch (short_option) {
3574       case 'a': {
3575         m_type = eLookupTypeAddress;
3576         m_addr = OptionArgParser::ToAddress(execution_context, option_arg,
3577                                             LLDB_INVALID_ADDRESS, &error);
3578       } break;
3579 
3580       case 'o':
3581         if (option_arg.getAsInteger(0, m_offset))
3582           error.SetErrorStringWithFormat("invalid offset string '%s'",
3583                                          option_arg.str().c_str());
3584         break;
3585 
3586       case 's':
3587         m_str = option_arg;
3588         m_type = eLookupTypeSymbol;
3589         break;
3590 
3591       case 'f':
3592         m_file.SetFile(option_arg, FileSpec::Style::native);
3593         m_type = eLookupTypeFileLine;
3594         break;
3595 
3596       case 'i':
3597         m_include_inlines = false;
3598         break;
3599 
3600       case 'l':
3601         if (option_arg.getAsInteger(0, m_line_number))
3602           error.SetErrorStringWithFormat("invalid line number string '%s'",
3603                                          option_arg.str().c_str());
3604         else if (m_line_number == 0)
3605           error.SetErrorString("zero is an invalid line number");
3606         m_type = eLookupTypeFileLine;
3607         break;
3608 
3609       case 'F':
3610         m_str = option_arg;
3611         m_type = eLookupTypeFunction;
3612         break;
3613 
3614       case 'n':
3615         m_str = option_arg;
3616         m_type = eLookupTypeFunctionOrSymbol;
3617         break;
3618 
3619       case 't':
3620         m_str = option_arg;
3621         m_type = eLookupTypeType;
3622         break;
3623 
3624       case 'v':
3625         m_verbose = true;
3626         break;
3627 
3628       case 'A':
3629         m_print_all = true;
3630         break;
3631 
3632       case 'r':
3633         m_use_regex = true;
3634         break;
3635       default:
3636         llvm_unreachable("Unimplemented option");
3637       }
3638 
3639       return error;
3640     }
3641 
3642     void OptionParsingStarting(ExecutionContext *execution_context) override {
3643       m_type = eLookupTypeInvalid;
3644       m_str.clear();
3645       m_file.Clear();
3646       m_addr = LLDB_INVALID_ADDRESS;
3647       m_offset = 0;
3648       m_line_number = 0;
3649       m_use_regex = false;
3650       m_include_inlines = true;
3651       m_verbose = false;
3652       m_print_all = false;
3653     }
3654 
3655     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
3656       return llvm::makeArrayRef(g_target_modules_lookup_options);
3657     }
3658 
3659     int m_type;        // Should be a eLookupTypeXXX enum after parsing options
3660     std::string m_str; // Holds name lookup
3661     FileSpec m_file;   // Files for file lookups
3662     lldb::addr_t m_addr; // Holds the address to lookup
3663     lldb::addr_t
3664         m_offset; // Subtract this offset from m_addr before doing lookups.
3665     uint32_t m_line_number; // Line number for file+line lookups
3666     bool m_use_regex;       // Name lookups in m_str are regular expressions.
3667     bool m_include_inlines; // Check for inline entries when looking up by
3668                             // file/line.
3669     bool m_verbose;         // Enable verbose lookup info
3670     bool m_print_all; // Print all matches, even in cases where there's a best
3671                       // match.
3672   };
3673 
3674   CommandObjectTargetModulesLookup(CommandInterpreter &interpreter)
3675       : CommandObjectParsed(interpreter, "target modules lookup",
3676                             "Look up information within executable and "
3677                             "dependent shared library images.",
3678                             nullptr, eCommandRequiresTarget),
3679         m_options() {
3680     CommandArgumentEntry arg;
3681     CommandArgumentData file_arg;
3682 
3683     // Define the first (and only) variant of this arg.
3684     file_arg.arg_type = eArgTypeFilename;
3685     file_arg.arg_repetition = eArgRepeatStar;
3686 
3687     // There is only one variant this argument could be; put it into the
3688     // argument entry.
3689     arg.push_back(file_arg);
3690 
3691     // Push the data for the first argument into the m_arguments vector.
3692     m_arguments.push_back(arg);
3693   }
3694 
3695   ~CommandObjectTargetModulesLookup() override = default;
3696 
3697   Options *GetOptions() override { return &m_options; }
3698 
3699   bool LookupHere(CommandInterpreter &interpreter, CommandReturnObject &result,
3700                   bool &syntax_error) {
3701     switch (m_options.m_type) {
3702     case eLookupTypeAddress:
3703     case eLookupTypeFileLine:
3704     case eLookupTypeFunction:
3705     case eLookupTypeFunctionOrSymbol:
3706     case eLookupTypeSymbol:
3707     default:
3708       return false;
3709     case eLookupTypeType:
3710       break;
3711     }
3712 
3713     StackFrameSP frame = m_exe_ctx.GetFrameSP();
3714 
3715     if (!frame)
3716       return false;
3717 
3718     const SymbolContext &sym_ctx(frame->GetSymbolContext(eSymbolContextModule));
3719 
3720     if (!sym_ctx.module_sp)
3721       return false;
3722 
3723     switch (m_options.m_type) {
3724     default:
3725       return false;
3726     case eLookupTypeType:
3727       if (!m_options.m_str.empty()) {
3728         if (LookupTypeHere(m_interpreter, result.GetOutputStream(),
3729                            *sym_ctx.module_sp, m_options.m_str.c_str(),
3730                            m_options.m_use_regex)) {
3731           result.SetStatus(eReturnStatusSuccessFinishResult);
3732           return true;
3733         }
3734       }
3735       break;
3736     }
3737 
3738     return true;
3739   }
3740 
3741   bool LookupInModule(CommandInterpreter &interpreter, Module *module,
3742                       CommandReturnObject &result, bool &syntax_error) {
3743     switch (m_options.m_type) {
3744     case eLookupTypeAddress:
3745       if (m_options.m_addr != LLDB_INVALID_ADDRESS) {
3746         if (LookupAddressInModule(
3747                 m_interpreter, result.GetOutputStream(), module,
3748                 eSymbolContextEverything |
3749                     (m_options.m_verbose
3750                          ? static_cast<int>(eSymbolContextVariable)
3751                          : 0),
3752                 m_options.m_addr, m_options.m_offset, m_options.m_verbose)) {
3753           result.SetStatus(eReturnStatusSuccessFinishResult);
3754           return true;
3755         }
3756       }
3757       break;
3758 
3759     case eLookupTypeSymbol:
3760       if (!m_options.m_str.empty()) {
3761         if (LookupSymbolInModule(m_interpreter, result.GetOutputStream(),
3762                                  module, m_options.m_str.c_str(),
3763                                  m_options.m_use_regex, m_options.m_verbose)) {
3764           result.SetStatus(eReturnStatusSuccessFinishResult);
3765           return true;
3766         }
3767       }
3768       break;
3769 
3770     case eLookupTypeFileLine:
3771       if (m_options.m_file) {
3772         if (LookupFileAndLineInModule(
3773                 m_interpreter, result.GetOutputStream(), module,
3774                 m_options.m_file, m_options.m_line_number,
3775                 m_options.m_include_inlines, m_options.m_verbose)) {
3776           result.SetStatus(eReturnStatusSuccessFinishResult);
3777           return true;
3778         }
3779       }
3780       break;
3781 
3782     case eLookupTypeFunctionOrSymbol:
3783     case eLookupTypeFunction:
3784       if (!m_options.m_str.empty()) {
3785         if (LookupFunctionInModule(
3786                 m_interpreter, result.GetOutputStream(), module,
3787                 m_options.m_str.c_str(), m_options.m_use_regex,
3788                 m_options.m_include_inlines,
3789                 m_options.m_type ==
3790                     eLookupTypeFunctionOrSymbol, // include symbols
3791                 m_options.m_verbose)) {
3792           result.SetStatus(eReturnStatusSuccessFinishResult);
3793           return true;
3794         }
3795       }
3796       break;
3797 
3798     case eLookupTypeType:
3799       if (!m_options.m_str.empty()) {
3800         if (LookupTypeInModule(m_interpreter, result.GetOutputStream(), module,
3801                                m_options.m_str.c_str(),
3802                                m_options.m_use_regex)) {
3803           result.SetStatus(eReturnStatusSuccessFinishResult);
3804           return true;
3805         }
3806       }
3807       break;
3808 
3809     default:
3810       m_options.GenerateOptionUsage(
3811           result.GetErrorStream(), this,
3812           GetCommandInterpreter().GetDebugger().GetTerminalWidth());
3813       syntax_error = true;
3814       break;
3815     }
3816 
3817     result.SetStatus(eReturnStatusFailed);
3818     return false;
3819   }
3820 
3821 protected:
3822   bool DoExecute(Args &command, CommandReturnObject &result) override {
3823     Target *target = &GetSelectedTarget();
3824     bool syntax_error = false;
3825     uint32_t i;
3826     uint32_t num_successful_lookups = 0;
3827     uint32_t addr_byte_size = target->GetArchitecture().GetAddressByteSize();
3828     result.GetOutputStream().SetAddressByteSize(addr_byte_size);
3829     result.GetErrorStream().SetAddressByteSize(addr_byte_size);
3830     // Dump all sections for all modules images
3831 
3832     if (command.GetArgumentCount() == 0) {
3833       ModuleSP current_module;
3834 
3835       // Where it is possible to look in the current symbol context first,
3836       // try that.  If this search was successful and --all was not passed,
3837       // don't print anything else.
3838       if (LookupHere(m_interpreter, result, syntax_error)) {
3839         result.GetOutputStream().EOL();
3840         num_successful_lookups++;
3841         if (!m_options.m_print_all) {
3842           result.SetStatus(eReturnStatusSuccessFinishResult);
3843           return result.Succeeded();
3844         }
3845       }
3846 
3847       // Dump all sections for all other modules
3848 
3849       const ModuleList &target_modules = target->GetImages();
3850       std::lock_guard<std::recursive_mutex> guard(target_modules.GetMutex());
3851       const size_t num_modules = target_modules.GetSize();
3852       if (num_modules > 0) {
3853         for (i = 0; i < num_modules && !syntax_error; ++i) {
3854           Module *module_pointer =
3855               target_modules.GetModulePointerAtIndexUnlocked(i);
3856 
3857           if (module_pointer != current_module.get() &&
3858               LookupInModule(m_interpreter,
3859                              target_modules.GetModulePointerAtIndexUnlocked(i),
3860                              result, syntax_error)) {
3861             result.GetOutputStream().EOL();
3862             num_successful_lookups++;
3863           }
3864         }
3865       } else {
3866         result.AppendError("the target has no associated executable images");
3867         result.SetStatus(eReturnStatusFailed);
3868         return false;
3869       }
3870     } else {
3871       // Dump specified images (by basename or fullpath)
3872       const char *arg_cstr;
3873       for (i = 0; (arg_cstr = command.GetArgumentAtIndex(i)) != nullptr &&
3874                   !syntax_error;
3875            ++i) {
3876         ModuleList module_list;
3877         const size_t num_matches =
3878             FindModulesByName(target, arg_cstr, module_list, false);
3879         if (num_matches > 0) {
3880           for (size_t j = 0; j < num_matches; ++j) {
3881             Module *module = module_list.GetModulePointerAtIndex(j);
3882             if (module) {
3883               if (LookupInModule(m_interpreter, module, result, syntax_error)) {
3884                 result.GetOutputStream().EOL();
3885                 num_successful_lookups++;
3886               }
3887             }
3888           }
3889         } else
3890           result.AppendWarningWithFormat(
3891               "Unable to find an image that matches '%s'.\n", arg_cstr);
3892       }
3893     }
3894 
3895     if (num_successful_lookups > 0)
3896       result.SetStatus(eReturnStatusSuccessFinishResult);
3897     else
3898       result.SetStatus(eReturnStatusFailed);
3899     return result.Succeeded();
3900   }
3901 
3902   CommandOptions m_options;
3903 };
3904 
3905 #pragma mark CommandObjectMultiwordImageSearchPaths
3906 
3907 // CommandObjectMultiwordImageSearchPaths
3908 
3909 class CommandObjectTargetModulesImageSearchPaths
3910     : public CommandObjectMultiword {
3911 public:
3912   CommandObjectTargetModulesImageSearchPaths(CommandInterpreter &interpreter)
3913       : CommandObjectMultiword(
3914             interpreter, "target modules search-paths",
3915             "Commands for managing module search paths for a target.",
3916             "target modules search-paths <subcommand> [<subcommand-options>]") {
3917     LoadSubCommand(
3918         "add", CommandObjectSP(
3919                    new CommandObjectTargetModulesSearchPathsAdd(interpreter)));
3920     LoadSubCommand(
3921         "clear", CommandObjectSP(new CommandObjectTargetModulesSearchPathsClear(
3922                      interpreter)));
3923     LoadSubCommand(
3924         "insert",
3925         CommandObjectSP(
3926             new CommandObjectTargetModulesSearchPathsInsert(interpreter)));
3927     LoadSubCommand(
3928         "list", CommandObjectSP(new CommandObjectTargetModulesSearchPathsList(
3929                     interpreter)));
3930     LoadSubCommand(
3931         "query", CommandObjectSP(new CommandObjectTargetModulesSearchPathsQuery(
3932                      interpreter)));
3933   }
3934 
3935   ~CommandObjectTargetModulesImageSearchPaths() override = default;
3936 };
3937 
3938 #pragma mark CommandObjectTargetModules
3939 
3940 // CommandObjectTargetModules
3941 
3942 class CommandObjectTargetModules : public CommandObjectMultiword {
3943 public:
3944   // Constructors and Destructors
3945   CommandObjectTargetModules(CommandInterpreter &interpreter)
3946       : CommandObjectMultiword(interpreter, "target modules",
3947                                "Commands for accessing information for one or "
3948                                "more target modules.",
3949                                "target modules <sub-command> ...") {
3950     LoadSubCommand(
3951         "add", CommandObjectSP(new CommandObjectTargetModulesAdd(interpreter)));
3952     LoadSubCommand("load", CommandObjectSP(new CommandObjectTargetModulesLoad(
3953                                interpreter)));
3954     LoadSubCommand("dump", CommandObjectSP(new CommandObjectTargetModulesDump(
3955                                interpreter)));
3956     LoadSubCommand("list", CommandObjectSP(new CommandObjectTargetModulesList(
3957                                interpreter)));
3958     LoadSubCommand(
3959         "lookup",
3960         CommandObjectSP(new CommandObjectTargetModulesLookup(interpreter)));
3961     LoadSubCommand(
3962         "search-paths",
3963         CommandObjectSP(
3964             new CommandObjectTargetModulesImageSearchPaths(interpreter)));
3965     LoadSubCommand(
3966         "show-unwind",
3967         CommandObjectSP(new CommandObjectTargetModulesShowUnwind(interpreter)));
3968   }
3969 
3970   ~CommandObjectTargetModules() override = default;
3971 
3972 private:
3973   // For CommandObjectTargetModules only
3974   DISALLOW_COPY_AND_ASSIGN(CommandObjectTargetModules);
3975 };
3976 
3977 class CommandObjectTargetSymbolsAdd : public CommandObjectParsed {
3978 public:
3979   CommandObjectTargetSymbolsAdd(CommandInterpreter &interpreter)
3980       : CommandObjectParsed(
3981             interpreter, "target symbols add",
3982             "Add a debug symbol file to one of the target's current modules by "
3983             "specifying a path to a debug symbols file, or using the options "
3984             "to specify a module to download symbols for.",
3985             "target symbols add <cmd-options> [<symfile>]",
3986             eCommandRequiresTarget),
3987         m_option_group(),
3988         m_file_option(
3989             LLDB_OPT_SET_1, false, "shlib", 's',
3990             CommandCompletions::eModuleCompletion, eArgTypeShlibName,
3991             "Fullpath or basename for module to find debug symbols for."),
3992         m_current_frame_option(
3993             LLDB_OPT_SET_2, false, "frame", 'F',
3994             "Locate the debug symbols the currently selected frame.", false,
3995             true)
3996 
3997   {
3998     m_option_group.Append(&m_uuid_option_group, LLDB_OPT_SET_ALL,
3999                           LLDB_OPT_SET_1);
4000     m_option_group.Append(&m_file_option, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4001     m_option_group.Append(&m_current_frame_option, LLDB_OPT_SET_2,
4002                           LLDB_OPT_SET_2);
4003     m_option_group.Finalize();
4004   }
4005 
4006   ~CommandObjectTargetSymbolsAdd() override = default;
4007 
4008   void
4009   HandleArgumentCompletion(CompletionRequest &request,
4010                            OptionElementVector &opt_element_vector) override {
4011     CommandCompletions::InvokeCommonCompletionCallbacks(
4012         GetCommandInterpreter(), CommandCompletions::eDiskFileCompletion,
4013         request, nullptr);
4014   }
4015 
4016   Options *GetOptions() override { return &m_option_group; }
4017 
4018 protected:
4019   bool AddModuleSymbols(Target *target, ModuleSpec &module_spec, bool &flush,
4020                         CommandReturnObject &result) {
4021     const FileSpec &symbol_fspec = module_spec.GetSymbolFileSpec();
4022     if (symbol_fspec) {
4023       char symfile_path[PATH_MAX];
4024       symbol_fspec.GetPath(symfile_path, sizeof(symfile_path));
4025 
4026       if (!module_spec.GetUUID().IsValid()) {
4027         if (!module_spec.GetFileSpec() && !module_spec.GetPlatformFileSpec())
4028           module_spec.GetFileSpec().GetFilename() = symbol_fspec.GetFilename();
4029       }
4030       // We now have a module that represents a symbol file that can be used
4031       // for a module that might exist in the current target, so we need to
4032       // find that module in the target
4033       ModuleList matching_module_list;
4034 
4035       size_t num_matches = 0;
4036       // First extract all module specs from the symbol file
4037       lldb_private::ModuleSpecList symfile_module_specs;
4038       if (ObjectFile::GetModuleSpecifications(module_spec.GetSymbolFileSpec(),
4039                                               0, 0, symfile_module_specs)) {
4040         // Now extract the module spec that matches the target architecture
4041         ModuleSpec target_arch_module_spec;
4042         ModuleSpec symfile_module_spec;
4043         target_arch_module_spec.GetArchitecture() = target->GetArchitecture();
4044         if (symfile_module_specs.FindMatchingModuleSpec(target_arch_module_spec,
4045                                                         symfile_module_spec)) {
4046           // See if it has a UUID?
4047           if (symfile_module_spec.GetUUID().IsValid()) {
4048             // It has a UUID, look for this UUID in the target modules
4049             ModuleSpec symfile_uuid_module_spec;
4050             symfile_uuid_module_spec.GetUUID() = symfile_module_spec.GetUUID();
4051             num_matches = target->GetImages().FindModules(
4052                 symfile_uuid_module_spec, matching_module_list);
4053           }
4054         }
4055 
4056         if (num_matches == 0) {
4057           // No matches yet, iterate through the module specs to find a UUID
4058           // value that we can match up to an image in our target
4059           const size_t num_symfile_module_specs =
4060               symfile_module_specs.GetSize();
4061           for (size_t i = 0; i < num_symfile_module_specs && num_matches == 0;
4062                ++i) {
4063             if (symfile_module_specs.GetModuleSpecAtIndex(
4064                     i, symfile_module_spec)) {
4065               if (symfile_module_spec.GetUUID().IsValid()) {
4066                 // It has a UUID, look for this UUID in the target modules
4067                 ModuleSpec symfile_uuid_module_spec;
4068                 symfile_uuid_module_spec.GetUUID() =
4069                     symfile_module_spec.GetUUID();
4070                 num_matches = target->GetImages().FindModules(
4071                     symfile_uuid_module_spec, matching_module_list);
4072               }
4073             }
4074           }
4075         }
4076       }
4077 
4078       // Just try to match up the file by basename if we have no matches at
4079       // this point
4080       if (num_matches == 0)
4081         num_matches =
4082             target->GetImages().FindModules(module_spec, matching_module_list);
4083 
4084       while (num_matches == 0) {
4085         ConstString filename_no_extension(
4086             module_spec.GetFileSpec().GetFileNameStrippingExtension());
4087         // Empty string returned, lets bail
4088         if (!filename_no_extension)
4089           break;
4090 
4091         // Check if there was no extension to strip and the basename is the
4092         // same
4093         if (filename_no_extension == module_spec.GetFileSpec().GetFilename())
4094           break;
4095 
4096         // Replace basename with one less extension
4097         module_spec.GetFileSpec().GetFilename() = filename_no_extension;
4098 
4099         num_matches =
4100             target->GetImages().FindModules(module_spec, matching_module_list);
4101       }
4102 
4103       if (num_matches > 1) {
4104         result.AppendErrorWithFormat("multiple modules match symbol file '%s', "
4105                                      "use the --uuid option to resolve the "
4106                                      "ambiguity.\n",
4107                                      symfile_path);
4108       } else if (num_matches == 1) {
4109         ModuleSP module_sp(matching_module_list.GetModuleAtIndex(0));
4110 
4111         // The module has not yet created its symbol vendor, we can just give
4112         // the existing target module the symfile path to use for when it
4113         // decides to create it!
4114         module_sp->SetSymbolFileFileSpec(symbol_fspec);
4115 
4116         SymbolFile *symbol_file =
4117             module_sp->GetSymbolFile(true, &result.GetErrorStream());
4118         if (symbol_file) {
4119           ObjectFile *object_file = symbol_file->GetObjectFile();
4120 
4121           if (object_file && object_file->GetFileSpec() == symbol_fspec) {
4122             // Provide feedback that the symfile has been successfully added.
4123             const FileSpec &module_fs = module_sp->GetFileSpec();
4124             result.AppendMessageWithFormat(
4125                 "symbol file '%s' has been added to '%s'\n", symfile_path,
4126                 module_fs.GetPath().c_str());
4127 
4128             // Let clients know something changed in the module if it is
4129             // currently loaded
4130             ModuleList module_list;
4131             module_list.Append(module_sp);
4132             target->SymbolsDidLoad(module_list);
4133 
4134             // Make sure we load any scripting resources that may be embedded
4135             // in the debug info files in case the platform supports that.
4136             Status error;
4137             StreamString feedback_stream;
4138             module_sp->LoadScriptingResourceInTarget(target, error,
4139                                                      &feedback_stream);
4140             if (error.Fail() && error.AsCString())
4141               result.AppendWarningWithFormat(
4142                   "unable to load scripting data for module %s - error "
4143                   "reported was %s",
4144                   module_sp->GetFileSpec()
4145                       .GetFileNameStrippingExtension()
4146                       .GetCString(),
4147                   error.AsCString());
4148             else if (feedback_stream.GetSize())
4149               result.AppendWarningWithFormat("%s", feedback_stream.GetData());
4150 
4151             flush = true;
4152             result.SetStatus(eReturnStatusSuccessFinishResult);
4153             return true;
4154           }
4155         }
4156         // Clear the symbol file spec if anything went wrong
4157         module_sp->SetSymbolFileFileSpec(FileSpec());
4158       }
4159 
4160       namespace fs = llvm::sys::fs;
4161       if (module_spec.GetUUID().IsValid()) {
4162         StreamString ss_symfile_uuid;
4163         module_spec.GetUUID().Dump(&ss_symfile_uuid);
4164         result.AppendErrorWithFormat(
4165             "symbol file '%s' (%s) does not match any existing module%s\n",
4166             symfile_path, ss_symfile_uuid.GetData(),
4167             !fs::is_regular_file(symbol_fspec.GetPath())
4168                 ? "\n       please specify the full path to the symbol file"
4169                 : "");
4170       } else {
4171         result.AppendErrorWithFormat(
4172             "symbol file '%s' does not match any existing module%s\n",
4173             symfile_path,
4174             !fs::is_regular_file(symbol_fspec.GetPath())
4175                 ? "\n       please specify the full path to the symbol file"
4176                 : "");
4177       }
4178     } else {
4179       result.AppendError(
4180           "one or more executable image paths must be specified");
4181     }
4182     result.SetStatus(eReturnStatusFailed);
4183     return false;
4184   }
4185 
4186   bool DoExecute(Args &args, CommandReturnObject &result) override {
4187     Target *target = m_exe_ctx.GetTargetPtr();
4188     result.SetStatus(eReturnStatusFailed);
4189     bool flush = false;
4190     ModuleSpec module_spec;
4191     const bool uuid_option_set =
4192         m_uuid_option_group.GetOptionValue().OptionWasSet();
4193     const bool file_option_set = m_file_option.GetOptionValue().OptionWasSet();
4194     const bool frame_option_set =
4195         m_current_frame_option.GetOptionValue().OptionWasSet();
4196     const size_t argc = args.GetArgumentCount();
4197 
4198     if (argc == 0) {
4199       if (uuid_option_set || file_option_set || frame_option_set) {
4200         bool success = false;
4201         bool error_set = false;
4202         if (frame_option_set) {
4203           Process *process = m_exe_ctx.GetProcessPtr();
4204           if (process) {
4205             const StateType process_state = process->GetState();
4206             if (StateIsStoppedState(process_state, true)) {
4207               StackFrame *frame = m_exe_ctx.GetFramePtr();
4208               if (frame) {
4209                 ModuleSP frame_module_sp(
4210                     frame->GetSymbolContext(eSymbolContextModule).module_sp);
4211                 if (frame_module_sp) {
4212                   if (FileSystem::Instance().Exists(
4213                           frame_module_sp->GetPlatformFileSpec())) {
4214                     module_spec.GetArchitecture() =
4215                         frame_module_sp->GetArchitecture();
4216                     module_spec.GetFileSpec() =
4217                         frame_module_sp->GetPlatformFileSpec();
4218                   }
4219                   module_spec.GetUUID() = frame_module_sp->GetUUID();
4220                   success = module_spec.GetUUID().IsValid() ||
4221                             module_spec.GetFileSpec();
4222                 } else {
4223                   result.AppendError("frame has no module");
4224                   error_set = true;
4225                 }
4226               } else {
4227                 result.AppendError("invalid current frame");
4228                 error_set = true;
4229               }
4230             } else {
4231               result.AppendErrorWithFormat("process is not stopped: %s",
4232                                            StateAsCString(process_state));
4233               error_set = true;
4234             }
4235           } else {
4236             result.AppendError(
4237                 "a process must exist in order to use the --frame option");
4238             error_set = true;
4239           }
4240         } else {
4241           if (uuid_option_set) {
4242             module_spec.GetUUID() =
4243                 m_uuid_option_group.GetOptionValue().GetCurrentValue();
4244             success |= module_spec.GetUUID().IsValid();
4245           } else if (file_option_set) {
4246             module_spec.GetFileSpec() =
4247                 m_file_option.GetOptionValue().GetCurrentValue();
4248             ModuleSP module_sp(
4249                 target->GetImages().FindFirstModule(module_spec));
4250             if (module_sp) {
4251               module_spec.GetFileSpec() = module_sp->GetFileSpec();
4252               module_spec.GetPlatformFileSpec() =
4253                   module_sp->GetPlatformFileSpec();
4254               module_spec.GetUUID() = module_sp->GetUUID();
4255               module_spec.GetArchitecture() = module_sp->GetArchitecture();
4256             } else {
4257               module_spec.GetArchitecture() = target->GetArchitecture();
4258             }
4259             success |= module_spec.GetUUID().IsValid() ||
4260                        FileSystem::Instance().Exists(module_spec.GetFileSpec());
4261           }
4262         }
4263 
4264         if (success) {
4265           if (Symbols::DownloadObjectAndSymbolFile(module_spec)) {
4266             if (module_spec.GetSymbolFileSpec())
4267               success = AddModuleSymbols(target, module_spec, flush, result);
4268           }
4269         }
4270 
4271         if (!success && !error_set) {
4272           StreamString error_strm;
4273           if (uuid_option_set) {
4274             error_strm.PutCString("unable to find debug symbols for UUID ");
4275             module_spec.GetUUID().Dump(&error_strm);
4276           } else if (file_option_set) {
4277             error_strm.PutCString(
4278                 "unable to find debug symbols for the executable file ");
4279             error_strm << module_spec.GetFileSpec();
4280           } else if (frame_option_set) {
4281             error_strm.PutCString(
4282                 "unable to find debug symbols for the current frame");
4283           }
4284           result.AppendError(error_strm.GetString());
4285         }
4286       } else {
4287         result.AppendError("one or more symbol file paths must be specified, "
4288                            "or options must be specified");
4289       }
4290     } else {
4291       if (uuid_option_set) {
4292         result.AppendError("specify either one or more paths to symbol files "
4293                            "or use the --uuid option without arguments");
4294       } else if (frame_option_set) {
4295         result.AppendError("specify either one or more paths to symbol files "
4296                            "or use the --frame option without arguments");
4297       } else if (file_option_set && argc > 1) {
4298         result.AppendError("specify at most one symbol file path when "
4299                            "--shlib option is set");
4300       } else {
4301         PlatformSP platform_sp(target->GetPlatform());
4302 
4303         for (auto &entry : args.entries()) {
4304           if (!entry.ref().empty()) {
4305             auto &symbol_file_spec = module_spec.GetSymbolFileSpec();
4306             symbol_file_spec.SetFile(entry.ref(), FileSpec::Style::native);
4307             FileSystem::Instance().Resolve(symbol_file_spec);
4308             if (file_option_set) {
4309               module_spec.GetFileSpec() =
4310                   m_file_option.GetOptionValue().GetCurrentValue();
4311             }
4312             if (platform_sp) {
4313               FileSpec symfile_spec;
4314               if (platform_sp
4315                       ->ResolveSymbolFile(*target, module_spec, symfile_spec)
4316                       .Success())
4317                 module_spec.GetSymbolFileSpec() = symfile_spec;
4318             }
4319 
4320             ArchSpec arch;
4321             bool symfile_exists =
4322                 FileSystem::Instance().Exists(module_spec.GetSymbolFileSpec());
4323 
4324             if (symfile_exists) {
4325               if (!AddModuleSymbols(target, module_spec, flush, result))
4326                 break;
4327             } else {
4328               std::string resolved_symfile_path =
4329                   module_spec.GetSymbolFileSpec().GetPath();
4330               if (resolved_symfile_path != entry.ref()) {
4331                 result.AppendErrorWithFormat(
4332                     "invalid module path '%s' with resolved path '%s'\n",
4333                     entry.c_str(), resolved_symfile_path.c_str());
4334                 break;
4335               }
4336               result.AppendErrorWithFormat("invalid module path '%s'\n",
4337                                            entry.c_str());
4338               break;
4339             }
4340           }
4341         }
4342       }
4343     }
4344 
4345     if (flush) {
4346       Process *process = m_exe_ctx.GetProcessPtr();
4347       if (process)
4348         process->Flush();
4349     }
4350     return result.Succeeded();
4351   }
4352 
4353   OptionGroupOptions m_option_group;
4354   OptionGroupUUID m_uuid_option_group;
4355   OptionGroupFile m_file_option;
4356   OptionGroupBoolean m_current_frame_option;
4357 };
4358 
4359 #pragma mark CommandObjectTargetSymbols
4360 
4361 // CommandObjectTargetSymbols
4362 
4363 class CommandObjectTargetSymbols : public CommandObjectMultiword {
4364 public:
4365   // Constructors and Destructors
4366   CommandObjectTargetSymbols(CommandInterpreter &interpreter)
4367       : CommandObjectMultiword(
4368             interpreter, "target symbols",
4369             "Commands for adding and managing debug symbol files.",
4370             "target symbols <sub-command> ...") {
4371     LoadSubCommand(
4372         "add", CommandObjectSP(new CommandObjectTargetSymbolsAdd(interpreter)));
4373   }
4374 
4375   ~CommandObjectTargetSymbols() override = default;
4376 
4377 private:
4378   // For CommandObjectTargetModules only
4379   DISALLOW_COPY_AND_ASSIGN(CommandObjectTargetSymbols);
4380 };
4381 
4382 #pragma mark CommandObjectTargetStopHookAdd
4383 
4384 // CommandObjectTargetStopHookAdd
4385 #define LLDB_OPTIONS_target_stop_hook_add
4386 #include "CommandOptions.inc"
4387 
4388 class CommandObjectTargetStopHookAdd : public CommandObjectParsed,
4389                                        public IOHandlerDelegateMultiline {
4390 public:
4391   class CommandOptions : public Options {
4392   public:
4393     CommandOptions()
4394         : Options(), m_line_start(0), m_line_end(UINT_MAX),
4395           m_func_name_type_mask(eFunctionNameTypeAuto),
4396           m_sym_ctx_specified(false), m_thread_specified(false),
4397           m_use_one_liner(false), m_one_liner() {}
4398 
4399     ~CommandOptions() override = default;
4400 
4401     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
4402       return llvm::makeArrayRef(g_target_stop_hook_add_options);
4403     }
4404 
4405     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
4406                           ExecutionContext *execution_context) override {
4407       Status error;
4408       const int short_option = m_getopt_table[option_idx].val;
4409 
4410       switch (short_option) {
4411       case 'c':
4412         m_class_name = option_arg;
4413         m_sym_ctx_specified = true;
4414         break;
4415 
4416       case 'e':
4417         if (option_arg.getAsInteger(0, m_line_end)) {
4418           error.SetErrorStringWithFormat("invalid end line number: \"%s\"",
4419                                          option_arg.str().c_str());
4420           break;
4421         }
4422         m_sym_ctx_specified = true;
4423         break;
4424 
4425       case 'G': {
4426         bool value, success;
4427         value = OptionArgParser::ToBoolean(option_arg, false, &success);
4428         if (success) {
4429           m_auto_continue = value;
4430         } else
4431           error.SetErrorStringWithFormat(
4432               "invalid boolean value '%s' passed for -G option",
4433               option_arg.str().c_str());
4434       }
4435       break;
4436       case 'l':
4437         if (option_arg.getAsInteger(0, m_line_start)) {
4438           error.SetErrorStringWithFormat("invalid start line number: \"%s\"",
4439                                          option_arg.str().c_str());
4440           break;
4441         }
4442         m_sym_ctx_specified = true;
4443         break;
4444 
4445       case 'i':
4446         m_no_inlines = true;
4447         break;
4448 
4449       case 'n':
4450         m_function_name = option_arg;
4451         m_func_name_type_mask |= eFunctionNameTypeAuto;
4452         m_sym_ctx_specified = true;
4453         break;
4454 
4455       case 'f':
4456         m_file_name = option_arg;
4457         m_sym_ctx_specified = true;
4458         break;
4459 
4460       case 's':
4461         m_module_name = option_arg;
4462         m_sym_ctx_specified = true;
4463         break;
4464 
4465       case 't':
4466         if (option_arg.getAsInteger(0, m_thread_id))
4467           error.SetErrorStringWithFormat("invalid thread id string '%s'",
4468                                          option_arg.str().c_str());
4469         m_thread_specified = true;
4470         break;
4471 
4472       case 'T':
4473         m_thread_name = option_arg;
4474         m_thread_specified = true;
4475         break;
4476 
4477       case 'q':
4478         m_queue_name = option_arg;
4479         m_thread_specified = true;
4480         break;
4481 
4482       case 'x':
4483         if (option_arg.getAsInteger(0, m_thread_index))
4484           error.SetErrorStringWithFormat("invalid thread index string '%s'",
4485                                          option_arg.str().c_str());
4486         m_thread_specified = true;
4487         break;
4488 
4489       case 'o':
4490         m_use_one_liner = true;
4491         m_one_liner.push_back(option_arg);
4492         break;
4493 
4494       default:
4495         llvm_unreachable("Unimplemented option");
4496       }
4497       return error;
4498     }
4499 
4500     void OptionParsingStarting(ExecutionContext *execution_context) override {
4501       m_class_name.clear();
4502       m_function_name.clear();
4503       m_line_start = 0;
4504       m_line_end = UINT_MAX;
4505       m_file_name.clear();
4506       m_module_name.clear();
4507       m_func_name_type_mask = eFunctionNameTypeAuto;
4508       m_thread_id = LLDB_INVALID_THREAD_ID;
4509       m_thread_index = UINT32_MAX;
4510       m_thread_name.clear();
4511       m_queue_name.clear();
4512 
4513       m_no_inlines = false;
4514       m_sym_ctx_specified = false;
4515       m_thread_specified = false;
4516 
4517       m_use_one_liner = false;
4518       m_one_liner.clear();
4519       m_auto_continue = false;
4520     }
4521 
4522     std::string m_class_name;
4523     std::string m_function_name;
4524     uint32_t m_line_start;
4525     uint32_t m_line_end;
4526     std::string m_file_name;
4527     std::string m_module_name;
4528     uint32_t m_func_name_type_mask; // A pick from lldb::FunctionNameType.
4529     lldb::tid_t m_thread_id;
4530     uint32_t m_thread_index;
4531     std::string m_thread_name;
4532     std::string m_queue_name;
4533     bool m_sym_ctx_specified;
4534     bool m_no_inlines;
4535     bool m_thread_specified;
4536     // Instance variables to hold the values for one_liner options.
4537     bool m_use_one_liner;
4538     std::vector<std::string> m_one_liner;
4539     bool m_auto_continue;
4540   };
4541 
4542   CommandObjectTargetStopHookAdd(CommandInterpreter &interpreter)
4543       : CommandObjectParsed(interpreter, "target stop-hook add",
4544                             "Add a hook to be executed when the target stops.",
4545                             "target stop-hook add"),
4546         IOHandlerDelegateMultiline("DONE",
4547                                    IOHandlerDelegate::Completion::LLDBCommand),
4548         m_options() {}
4549 
4550   ~CommandObjectTargetStopHookAdd() override = default;
4551 
4552   Options *GetOptions() override { return &m_options; }
4553 
4554 protected:
4555   void IOHandlerActivated(IOHandler &io_handler, bool interactive) override {
4556     StreamFileSP output_sp(io_handler.GetOutputStreamFileSP());
4557     if (output_sp && interactive) {
4558       output_sp->PutCString(
4559           "Enter your stop hook command(s).  Type 'DONE' to end.\n");
4560       output_sp->Flush();
4561     }
4562   }
4563 
4564   void IOHandlerInputComplete(IOHandler &io_handler,
4565                               std::string &line) override {
4566     if (m_stop_hook_sp) {
4567       if (line.empty()) {
4568         StreamFileSP error_sp(io_handler.GetErrorStreamFileSP());
4569         if (error_sp) {
4570           error_sp->Printf("error: stop hook #%" PRIu64
4571                            " aborted, no commands.\n",
4572                            m_stop_hook_sp->GetID());
4573           error_sp->Flush();
4574         }
4575         Target *target = GetDebugger().GetSelectedTarget().get();
4576         if (target)
4577           target->RemoveStopHookByID(m_stop_hook_sp->GetID());
4578       } else {
4579         m_stop_hook_sp->GetCommandPointer()->SplitIntoLines(line);
4580         StreamFileSP output_sp(io_handler.GetOutputStreamFileSP());
4581         if (output_sp) {
4582           output_sp->Printf("Stop hook #%" PRIu64 " added.\n",
4583                             m_stop_hook_sp->GetID());
4584           output_sp->Flush();
4585         }
4586       }
4587       m_stop_hook_sp.reset();
4588     }
4589     io_handler.SetIsDone(true);
4590   }
4591 
4592   bool DoExecute(Args &command, CommandReturnObject &result) override {
4593     m_stop_hook_sp.reset();
4594 
4595     Target &target = GetSelectedOrDummyTarget();
4596     Target::StopHookSP new_hook_sp = target.CreateStopHook();
4597 
4598     //  First step, make the specifier.
4599     std::unique_ptr<SymbolContextSpecifier> specifier_up;
4600     if (m_options.m_sym_ctx_specified) {
4601       specifier_up.reset(
4602           new SymbolContextSpecifier(GetDebugger().GetSelectedTarget()));
4603 
4604       if (!m_options.m_module_name.empty()) {
4605         specifier_up->AddSpecification(
4606             m_options.m_module_name.c_str(),
4607             SymbolContextSpecifier::eModuleSpecified);
4608       }
4609 
4610       if (!m_options.m_class_name.empty()) {
4611         specifier_up->AddSpecification(
4612             m_options.m_class_name.c_str(),
4613             SymbolContextSpecifier::eClassOrNamespaceSpecified);
4614       }
4615 
4616       if (!m_options.m_file_name.empty()) {
4617         specifier_up->AddSpecification(m_options.m_file_name.c_str(),
4618                                        SymbolContextSpecifier::eFileSpecified);
4619       }
4620 
4621       if (m_options.m_line_start != 0) {
4622         specifier_up->AddLineSpecification(
4623             m_options.m_line_start,
4624             SymbolContextSpecifier::eLineStartSpecified);
4625       }
4626 
4627       if (m_options.m_line_end != UINT_MAX) {
4628         specifier_up->AddLineSpecification(
4629             m_options.m_line_end, SymbolContextSpecifier::eLineEndSpecified);
4630       }
4631 
4632       if (!m_options.m_function_name.empty()) {
4633         specifier_up->AddSpecification(
4634             m_options.m_function_name.c_str(),
4635             SymbolContextSpecifier::eFunctionSpecified);
4636       }
4637     }
4638 
4639       if (specifier_up)
4640         new_hook_sp->SetSpecifier(specifier_up.release());
4641 
4642       // Next see if any of the thread options have been entered:
4643 
4644       if (m_options.m_thread_specified) {
4645         ThreadSpec *thread_spec = new ThreadSpec();
4646 
4647         if (m_options.m_thread_id != LLDB_INVALID_THREAD_ID) {
4648           thread_spec->SetTID(m_options.m_thread_id);
4649         }
4650 
4651         if (m_options.m_thread_index != UINT32_MAX)
4652           thread_spec->SetIndex(m_options.m_thread_index);
4653 
4654         if (!m_options.m_thread_name.empty())
4655           thread_spec->SetName(m_options.m_thread_name.c_str());
4656 
4657         if (!m_options.m_queue_name.empty())
4658           thread_spec->SetQueueName(m_options.m_queue_name.c_str());
4659 
4660         new_hook_sp->SetThreadSpecifier(thread_spec);
4661       }
4662 
4663       new_hook_sp->SetAutoContinue(m_options.m_auto_continue);
4664       if (m_options.m_use_one_liner) {
4665         // Use one-liners.
4666         for (auto cmd : m_options.m_one_liner)
4667           new_hook_sp->GetCommandPointer()->AppendString(
4668             cmd.c_str());
4669         result.AppendMessageWithFormat("Stop hook #%" PRIu64 " added.\n",
4670                                        new_hook_sp->GetID());
4671       } else {
4672         m_stop_hook_sp = new_hook_sp;
4673         m_interpreter.GetLLDBCommandsFromIOHandler(
4674             "> ",     // Prompt
4675             *this,    // IOHandlerDelegate
4676             true,     // Run IOHandler in async mode
4677             nullptr); // Baton for the "io_handler" that will be passed back
4678                       // into our IOHandlerDelegate functions
4679       }
4680       result.SetStatus(eReturnStatusSuccessFinishNoResult);
4681 
4682     return result.Succeeded();
4683   }
4684 
4685 private:
4686   CommandOptions m_options;
4687   Target::StopHookSP m_stop_hook_sp;
4688 };
4689 
4690 #pragma mark CommandObjectTargetStopHookDelete
4691 
4692 // CommandObjectTargetStopHookDelete
4693 
4694 class CommandObjectTargetStopHookDelete : public CommandObjectParsed {
4695 public:
4696   CommandObjectTargetStopHookDelete(CommandInterpreter &interpreter)
4697       : CommandObjectParsed(interpreter, "target stop-hook delete",
4698                             "Delete a stop-hook.",
4699                             "target stop-hook delete [<idx>]") {}
4700 
4701   ~CommandObjectTargetStopHookDelete() override = default;
4702 
4703 protected:
4704   bool DoExecute(Args &command, CommandReturnObject &result) override {
4705     Target &target = GetSelectedOrDummyTarget();
4706     // FIXME: see if we can use the breakpoint id style parser?
4707     size_t num_args = command.GetArgumentCount();
4708     if (num_args == 0) {
4709       if (!m_interpreter.Confirm("Delete all stop hooks?", true)) {
4710         result.SetStatus(eReturnStatusFailed);
4711         return false;
4712       } else {
4713         target.RemoveAllStopHooks();
4714       }
4715     } else {
4716       bool success;
4717       for (size_t i = 0; i < num_args; i++) {
4718         lldb::user_id_t user_id = StringConvert::ToUInt32(
4719             command.GetArgumentAtIndex(i), 0, 0, &success);
4720         if (!success) {
4721           result.AppendErrorWithFormat("invalid stop hook id: \"%s\".\n",
4722                                        command.GetArgumentAtIndex(i));
4723           result.SetStatus(eReturnStatusFailed);
4724           return false;
4725         }
4726         success = target.RemoveStopHookByID(user_id);
4727         if (!success) {
4728           result.AppendErrorWithFormat("unknown stop hook id: \"%s\".\n",
4729                                        command.GetArgumentAtIndex(i));
4730           result.SetStatus(eReturnStatusFailed);
4731           return false;
4732         }
4733       }
4734     }
4735       result.SetStatus(eReturnStatusSuccessFinishNoResult);
4736     return result.Succeeded();
4737   }
4738 };
4739 
4740 #pragma mark CommandObjectTargetStopHookEnableDisable
4741 
4742 // CommandObjectTargetStopHookEnableDisable
4743 
4744 class CommandObjectTargetStopHookEnableDisable : public CommandObjectParsed {
4745 public:
4746   CommandObjectTargetStopHookEnableDisable(CommandInterpreter &interpreter,
4747                                            bool enable, const char *name,
4748                                            const char *help, const char *syntax)
4749       : CommandObjectParsed(interpreter, name, help, syntax), m_enable(enable) {
4750   }
4751 
4752   ~CommandObjectTargetStopHookEnableDisable() override = default;
4753 
4754 protected:
4755   bool DoExecute(Args &command, CommandReturnObject &result) override {
4756     Target &target = GetSelectedOrDummyTarget();
4757     // FIXME: see if we can use the breakpoint id style parser?
4758     size_t num_args = command.GetArgumentCount();
4759     bool success;
4760 
4761     if (num_args == 0) {
4762       target.SetAllStopHooksActiveState(m_enable);
4763     } else {
4764       for (size_t i = 0; i < num_args; i++) {
4765         lldb::user_id_t user_id = StringConvert::ToUInt32(
4766             command.GetArgumentAtIndex(i), 0, 0, &success);
4767         if (!success) {
4768           result.AppendErrorWithFormat("invalid stop hook id: \"%s\".\n",
4769                                        command.GetArgumentAtIndex(i));
4770           result.SetStatus(eReturnStatusFailed);
4771           return false;
4772         }
4773         success = target.SetStopHookActiveStateByID(user_id, m_enable);
4774         if (!success) {
4775           result.AppendErrorWithFormat("unknown stop hook id: \"%s\".\n",
4776                                        command.GetArgumentAtIndex(i));
4777           result.SetStatus(eReturnStatusFailed);
4778           return false;
4779         }
4780       }
4781     }
4782       result.SetStatus(eReturnStatusSuccessFinishNoResult);
4783     return result.Succeeded();
4784   }
4785 
4786 private:
4787   bool m_enable;
4788 };
4789 
4790 #pragma mark CommandObjectTargetStopHookList
4791 
4792 // CommandObjectTargetStopHookList
4793 
4794 class CommandObjectTargetStopHookList : public CommandObjectParsed {
4795 public:
4796   CommandObjectTargetStopHookList(CommandInterpreter &interpreter)
4797       : CommandObjectParsed(interpreter, "target stop-hook list",
4798                             "List all stop-hooks.",
4799                             "target stop-hook list [<type>]") {}
4800 
4801   ~CommandObjectTargetStopHookList() override = default;
4802 
4803 protected:
4804   bool DoExecute(Args &command, CommandReturnObject &result) override {
4805     Target &target = GetSelectedOrDummyTarget();
4806 
4807     size_t num_hooks = target.GetNumStopHooks();
4808     if (num_hooks == 0) {
4809       result.GetOutputStream().PutCString("No stop hooks.\n");
4810     } else {
4811       for (size_t i = 0; i < num_hooks; i++) {
4812         Target::StopHookSP this_hook = target.GetStopHookAtIndex(i);
4813         if (i > 0)
4814           result.GetOutputStream().PutCString("\n");
4815         this_hook->GetDescription(&(result.GetOutputStream()),
4816                                   eDescriptionLevelFull);
4817       }
4818     }
4819     result.SetStatus(eReturnStatusSuccessFinishResult);
4820     return result.Succeeded();
4821   }
4822 };
4823 
4824 #pragma mark CommandObjectMultiwordTargetStopHooks
4825 
4826 // CommandObjectMultiwordTargetStopHooks
4827 
4828 class CommandObjectMultiwordTargetStopHooks : public CommandObjectMultiword {
4829 public:
4830   CommandObjectMultiwordTargetStopHooks(CommandInterpreter &interpreter)
4831       : CommandObjectMultiword(
4832             interpreter, "target stop-hook",
4833             "Commands for operating on debugger target stop-hooks.",
4834             "target stop-hook <subcommand> [<subcommand-options>]") {
4835     LoadSubCommand("add", CommandObjectSP(
4836                               new CommandObjectTargetStopHookAdd(interpreter)));
4837     LoadSubCommand(
4838         "delete",
4839         CommandObjectSP(new CommandObjectTargetStopHookDelete(interpreter)));
4840     LoadSubCommand("disable",
4841                    CommandObjectSP(new CommandObjectTargetStopHookEnableDisable(
4842                        interpreter, false, "target stop-hook disable [<id>]",
4843                        "Disable a stop-hook.", "target stop-hook disable")));
4844     LoadSubCommand("enable",
4845                    CommandObjectSP(new CommandObjectTargetStopHookEnableDisable(
4846                        interpreter, true, "target stop-hook enable [<id>]",
4847                        "Enable a stop-hook.", "target stop-hook enable")));
4848     LoadSubCommand("list", CommandObjectSP(new CommandObjectTargetStopHookList(
4849                                interpreter)));
4850   }
4851 
4852   ~CommandObjectMultiwordTargetStopHooks() override = default;
4853 };
4854 
4855 #pragma mark CommandObjectMultiwordTarget
4856 
4857 // CommandObjectMultiwordTarget
4858 
4859 CommandObjectMultiwordTarget::CommandObjectMultiwordTarget(
4860     CommandInterpreter &interpreter)
4861     : CommandObjectMultiword(interpreter, "target",
4862                              "Commands for operating on debugger targets.",
4863                              "target <subcommand> [<subcommand-options>]") {
4864   LoadSubCommand("create",
4865                  CommandObjectSP(new CommandObjectTargetCreate(interpreter)));
4866   LoadSubCommand("delete",
4867                  CommandObjectSP(new CommandObjectTargetDelete(interpreter)));
4868   LoadSubCommand("list",
4869                  CommandObjectSP(new CommandObjectTargetList(interpreter)));
4870   LoadSubCommand("select",
4871                  CommandObjectSP(new CommandObjectTargetSelect(interpreter)));
4872   LoadSubCommand(
4873       "stop-hook",
4874       CommandObjectSP(new CommandObjectMultiwordTargetStopHooks(interpreter)));
4875   LoadSubCommand("modules",
4876                  CommandObjectSP(new CommandObjectTargetModules(interpreter)));
4877   LoadSubCommand("symbols",
4878                  CommandObjectSP(new CommandObjectTargetSymbols(interpreter)));
4879   LoadSubCommand("variable",
4880                  CommandObjectSP(new CommandObjectTargetVariable(interpreter)));
4881 }
4882 
4883 CommandObjectMultiwordTarget::~CommandObjectMultiwordTarget() = default;
4884