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