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(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                     "."); // Any global with at least one character
945                 VariableList variable_list;
946                 sc.module_sp->FindGlobalVariables(all_globals_regex, append,
947                                                   UINT32_MAX, variable_list);
948                 DumpGlobalVariableList(m_exe_ctx, sc, variable_list, s);
949               }
950             }
951           }
952         }
953       }
954     }
955 
956     if (m_interpreter.TruncationWarningNecessary()) {
957       result.GetOutputStream().Printf(m_interpreter.TruncationWarningText(),
958                                       m_cmd_name.c_str());
959       m_interpreter.TruncationWarningGiven();
960     }
961 
962     return result.Succeeded();
963   }
964 
965   OptionGroupOptions m_option_group;
966   OptionGroupVariable m_option_variable;
967   OptionGroupFormat m_option_format;
968   OptionGroupFileList m_option_compile_units;
969   OptionGroupFileList m_option_shared_libraries;
970   OptionGroupValueObjectDisplay m_varobj_options;
971 };
972 
973 #pragma mark CommandObjectTargetModulesSearchPathsAdd
974 
975 class CommandObjectTargetModulesSearchPathsAdd : public CommandObjectParsed {
976 public:
977   CommandObjectTargetModulesSearchPathsAdd(CommandInterpreter &interpreter)
978       : CommandObjectParsed(interpreter, "target modules search-paths add",
979                             "Add new image search paths substitution pairs to "
980                             "the current target.",
981                             nullptr) {
982     CommandArgumentEntry arg;
983     CommandArgumentData old_prefix_arg;
984     CommandArgumentData new_prefix_arg;
985 
986     // Define the first variant of this arg pair.
987     old_prefix_arg.arg_type = eArgTypeOldPathPrefix;
988     old_prefix_arg.arg_repetition = eArgRepeatPairPlus;
989 
990     // Define the first variant of this arg pair.
991     new_prefix_arg.arg_type = eArgTypeNewPathPrefix;
992     new_prefix_arg.arg_repetition = eArgRepeatPairPlus;
993 
994     // There are two required arguments that must always occur together, i.e. an
995     // argument "pair".  Because they
996     // must always occur together, they are treated as two variants of one
997     // argument rather than two independent
998     // arguments.  Push them both into the first argument position for
999     // m_arguments...
1000 
1001     arg.push_back(old_prefix_arg);
1002     arg.push_back(new_prefix_arg);
1003 
1004     m_arguments.push_back(arg);
1005   }
1006 
1007   ~CommandObjectTargetModulesSearchPathsAdd() override = default;
1008 
1009 protected:
1010   bool DoExecute(Args &command, CommandReturnObject &result) override {
1011     Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
1012     if (target) {
1013       const size_t argc = command.GetArgumentCount();
1014       if (argc & 1) {
1015         result.AppendError("add requires an even number of arguments\n");
1016         result.SetStatus(eReturnStatusFailed);
1017       } else {
1018         for (size_t i = 0; i < argc; i += 2) {
1019           const char *from = command.GetArgumentAtIndex(i);
1020           const char *to = command.GetArgumentAtIndex(i + 1);
1021 
1022           if (from[0] && to[0]) {
1023             Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST);
1024             if (log) {
1025               log->Printf("target modules search path adding ImageSearchPath "
1026                           "pair: '%s' -> '%s'",
1027                           from, to);
1028             }
1029             bool last_pair = ((argc - i) == 2);
1030             target->GetImageSearchPathList().Append(
1031                 ConstString(from), ConstString(to),
1032                 last_pair); // Notify if this is the last pair
1033             result.SetStatus(eReturnStatusSuccessFinishNoResult);
1034           } else {
1035             if (from[0])
1036               result.AppendError("<path-prefix> can't be empty\n");
1037             else
1038               result.AppendError("<new-path-prefix> can't be empty\n");
1039             result.SetStatus(eReturnStatusFailed);
1040           }
1041         }
1042       }
1043     } else {
1044       result.AppendError("invalid target\n");
1045       result.SetStatus(eReturnStatusFailed);
1046     }
1047     return result.Succeeded();
1048   }
1049 };
1050 
1051 #pragma mark CommandObjectTargetModulesSearchPathsClear
1052 
1053 class CommandObjectTargetModulesSearchPathsClear : public CommandObjectParsed {
1054 public:
1055   CommandObjectTargetModulesSearchPathsClear(CommandInterpreter &interpreter)
1056       : CommandObjectParsed(interpreter, "target modules search-paths clear",
1057                             "Clear all current image search path substitution "
1058                             "pairs from the current target.",
1059                             "target modules search-paths clear") {}
1060 
1061   ~CommandObjectTargetModulesSearchPathsClear() override = default;
1062 
1063 protected:
1064   bool DoExecute(Args &command, CommandReturnObject &result) override {
1065     Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
1066     if (target) {
1067       bool notify = true;
1068       target->GetImageSearchPathList().Clear(notify);
1069       result.SetStatus(eReturnStatusSuccessFinishNoResult);
1070     } else {
1071       result.AppendError("invalid target\n");
1072       result.SetStatus(eReturnStatusFailed);
1073     }
1074     return result.Succeeded();
1075   }
1076 };
1077 
1078 #pragma mark CommandObjectTargetModulesSearchPathsInsert
1079 
1080 class CommandObjectTargetModulesSearchPathsInsert : public CommandObjectParsed {
1081 public:
1082   CommandObjectTargetModulesSearchPathsInsert(CommandInterpreter &interpreter)
1083       : CommandObjectParsed(interpreter, "target modules search-paths insert",
1084                             "Insert a new image search path substitution pair "
1085                             "into the current target at the specified index.",
1086                             nullptr) {
1087     CommandArgumentEntry arg1;
1088     CommandArgumentEntry arg2;
1089     CommandArgumentData index_arg;
1090     CommandArgumentData old_prefix_arg;
1091     CommandArgumentData new_prefix_arg;
1092 
1093     // Define the first and only variant of this arg.
1094     index_arg.arg_type = eArgTypeIndex;
1095     index_arg.arg_repetition = eArgRepeatPlain;
1096 
1097     // Put the one and only variant into the first arg for m_arguments:
1098     arg1.push_back(index_arg);
1099 
1100     // Define the first variant of this arg pair.
1101     old_prefix_arg.arg_type = eArgTypeOldPathPrefix;
1102     old_prefix_arg.arg_repetition = eArgRepeatPairPlus;
1103 
1104     // Define the first variant of this arg pair.
1105     new_prefix_arg.arg_type = eArgTypeNewPathPrefix;
1106     new_prefix_arg.arg_repetition = eArgRepeatPairPlus;
1107 
1108     // There are two required arguments that must always occur together, i.e. an
1109     // argument "pair".  Because they
1110     // must always occur together, they are treated as two variants of one
1111     // argument rather than two independent
1112     // arguments.  Push them both into the same argument position for
1113     // m_arguments...
1114 
1115     arg2.push_back(old_prefix_arg);
1116     arg2.push_back(new_prefix_arg);
1117 
1118     // Add arguments to m_arguments.
1119     m_arguments.push_back(arg1);
1120     m_arguments.push_back(arg2);
1121   }
1122 
1123   ~CommandObjectTargetModulesSearchPathsInsert() override = default;
1124 
1125 protected:
1126   bool DoExecute(Args &command, CommandReturnObject &result) override {
1127     Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
1128     if (target) {
1129       size_t argc = command.GetArgumentCount();
1130       // check for at least 3 arguments and an odd number of parameters
1131       if (argc >= 3 && argc & 1) {
1132         bool success = false;
1133 
1134         uint32_t insert_idx = StringConvert::ToUInt32(
1135             command.GetArgumentAtIndex(0), UINT32_MAX, 0, &success);
1136 
1137         if (!success) {
1138           result.AppendErrorWithFormat(
1139               "<index> parameter is not an integer: '%s'.\n",
1140               command.GetArgumentAtIndex(0));
1141           result.SetStatus(eReturnStatusFailed);
1142           return result.Succeeded();
1143         }
1144 
1145         // shift off the index
1146         command.Shift();
1147         argc = command.GetArgumentCount();
1148 
1149         for (uint32_t i = 0; i < argc; i += 2, ++insert_idx) {
1150           const char *from = command.GetArgumentAtIndex(i);
1151           const char *to = command.GetArgumentAtIndex(i + 1);
1152 
1153           if (from[0] && to[0]) {
1154             bool last_pair = ((argc - i) == 2);
1155             target->GetImageSearchPathList().Insert(
1156                 ConstString(from), ConstString(to), insert_idx, last_pair);
1157             result.SetStatus(eReturnStatusSuccessFinishNoResult);
1158           } else {
1159             if (from[0])
1160               result.AppendError("<path-prefix> can't be empty\n");
1161             else
1162               result.AppendError("<new-path-prefix> can't be empty\n");
1163             result.SetStatus(eReturnStatusFailed);
1164             return false;
1165           }
1166         }
1167       } else {
1168         result.AppendError("insert requires at least three arguments\n");
1169         result.SetStatus(eReturnStatusFailed);
1170         return result.Succeeded();
1171       }
1172 
1173     } else {
1174       result.AppendError("invalid target\n");
1175       result.SetStatus(eReturnStatusFailed);
1176     }
1177     return result.Succeeded();
1178   }
1179 };
1180 
1181 #pragma mark CommandObjectTargetModulesSearchPathsList
1182 
1183 class CommandObjectTargetModulesSearchPathsList : public CommandObjectParsed {
1184 public:
1185   CommandObjectTargetModulesSearchPathsList(CommandInterpreter &interpreter)
1186       : CommandObjectParsed(interpreter, "target modules search-paths list",
1187                             "List all current image search path substitution "
1188                             "pairs in the current target.",
1189                             "target modules search-paths list") {}
1190 
1191   ~CommandObjectTargetModulesSearchPathsList() override = default;
1192 
1193 protected:
1194   bool DoExecute(Args &command, CommandReturnObject &result) override {
1195     Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
1196     if (target) {
1197       if (command.GetArgumentCount() != 0) {
1198         result.AppendError("list takes no arguments\n");
1199         result.SetStatus(eReturnStatusFailed);
1200         return result.Succeeded();
1201       }
1202 
1203       target->GetImageSearchPathList().Dump(&result.GetOutputStream());
1204       result.SetStatus(eReturnStatusSuccessFinishResult);
1205     } else {
1206       result.AppendError("invalid target\n");
1207       result.SetStatus(eReturnStatusFailed);
1208     }
1209     return result.Succeeded();
1210   }
1211 };
1212 
1213 #pragma mark CommandObjectTargetModulesSearchPathsQuery
1214 
1215 class CommandObjectTargetModulesSearchPathsQuery : public CommandObjectParsed {
1216 public:
1217   CommandObjectTargetModulesSearchPathsQuery(CommandInterpreter &interpreter)
1218       : CommandObjectParsed(
1219             interpreter, "target modules search-paths query",
1220             "Transform a path using the first applicable image search path.",
1221             nullptr) {
1222     CommandArgumentEntry arg;
1223     CommandArgumentData path_arg;
1224 
1225     // Define the first (and only) variant of this arg.
1226     path_arg.arg_type = eArgTypeDirectoryName;
1227     path_arg.arg_repetition = eArgRepeatPlain;
1228 
1229     // There is only one variant this argument could be; put it into the
1230     // argument entry.
1231     arg.push_back(path_arg);
1232 
1233     // Push the data for the first argument into the m_arguments vector.
1234     m_arguments.push_back(arg);
1235   }
1236 
1237   ~CommandObjectTargetModulesSearchPathsQuery() override = default;
1238 
1239 protected:
1240   bool DoExecute(Args &command, CommandReturnObject &result) override {
1241     Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
1242     if (target) {
1243       if (command.GetArgumentCount() != 1) {
1244         result.AppendError("query requires one argument\n");
1245         result.SetStatus(eReturnStatusFailed);
1246         return result.Succeeded();
1247       }
1248 
1249       ConstString orig(command.GetArgumentAtIndex(0));
1250       ConstString transformed;
1251       if (target->GetImageSearchPathList().RemapPath(orig, transformed))
1252         result.GetOutputStream().Printf("%s\n", transformed.GetCString());
1253       else
1254         result.GetOutputStream().Printf("%s\n", orig.GetCString());
1255 
1256       result.SetStatus(eReturnStatusSuccessFinishResult);
1257     } else {
1258       result.AppendError("invalid target\n");
1259       result.SetStatus(eReturnStatusFailed);
1260     }
1261     return result.Succeeded();
1262   }
1263 };
1264 
1265 //----------------------------------------------------------------------
1266 // Static Helper functions
1267 //----------------------------------------------------------------------
1268 static void DumpModuleArchitecture(Stream &strm, Module *module,
1269                                    bool full_triple, uint32_t width) {
1270   if (module) {
1271     StreamString arch_strm;
1272 
1273     if (full_triple)
1274       module->GetArchitecture().DumpTriple(arch_strm);
1275     else
1276       arch_strm.PutCString(module->GetArchitecture().GetArchitectureName());
1277     std::string arch_str = arch_strm.GetString();
1278 
1279     if (width)
1280       strm.Printf("%-*s", width, arch_str.c_str());
1281     else
1282       strm.PutCString(arch_str.c_str());
1283   }
1284 }
1285 
1286 static void DumpModuleUUID(Stream &strm, Module *module) {
1287   if (module && module->GetUUID().IsValid())
1288     module->GetUUID().Dump(&strm);
1289   else
1290     strm.PutCString("                                    ");
1291 }
1292 
1293 static uint32_t DumpCompileUnitLineTable(CommandInterpreter &interpreter,
1294                                          Stream &strm, Module *module,
1295                                          const FileSpec &file_spec,
1296                                          bool load_addresses) {
1297   uint32_t num_matches = 0;
1298   if (module) {
1299     SymbolContextList sc_list;
1300     num_matches = module->ResolveSymbolContextsForFileSpec(
1301         file_spec, 0, false, eSymbolContextCompUnit, sc_list);
1302 
1303     for (uint32_t i = 0; i < num_matches; ++i) {
1304       SymbolContext sc;
1305       if (sc_list.GetContextAtIndex(i, sc)) {
1306         if (i > 0)
1307           strm << "\n\n";
1308 
1309         strm << "Line table for " << *static_cast<FileSpec *>(sc.comp_unit)
1310              << " in `" << module->GetFileSpec().GetFilename() << "\n";
1311         LineTable *line_table = sc.comp_unit->GetLineTable();
1312         if (line_table)
1313           line_table->GetDescription(
1314               &strm, interpreter.GetExecutionContext().GetTargetPtr(),
1315               lldb::eDescriptionLevelBrief);
1316         else
1317           strm << "No line table";
1318       }
1319     }
1320   }
1321   return num_matches;
1322 }
1323 
1324 static void DumpFullpath(Stream &strm, const FileSpec *file_spec_ptr,
1325                          uint32_t width) {
1326   if (file_spec_ptr) {
1327     if (width > 0) {
1328       std::string fullpath = file_spec_ptr->GetPath();
1329       strm.Printf("%-*s", width, fullpath.c_str());
1330       return;
1331     } else {
1332       file_spec_ptr->Dump(&strm);
1333       return;
1334     }
1335   }
1336   // Keep the width spacing correct if things go wrong...
1337   if (width > 0)
1338     strm.Printf("%-*s", width, "");
1339 }
1340 
1341 static void DumpDirectory(Stream &strm, const FileSpec *file_spec_ptr,
1342                           uint32_t width) {
1343   if (file_spec_ptr) {
1344     if (width > 0)
1345       strm.Printf("%-*s", width, file_spec_ptr->GetDirectory().AsCString(""));
1346     else
1347       file_spec_ptr->GetDirectory().Dump(&strm);
1348     return;
1349   }
1350   // Keep the width spacing correct if things go wrong...
1351   if (width > 0)
1352     strm.Printf("%-*s", width, "");
1353 }
1354 
1355 static void DumpBasename(Stream &strm, const FileSpec *file_spec_ptr,
1356                          uint32_t width) {
1357   if (file_spec_ptr) {
1358     if (width > 0)
1359       strm.Printf("%-*s", width, file_spec_ptr->GetFilename().AsCString(""));
1360     else
1361       file_spec_ptr->GetFilename().Dump(&strm);
1362     return;
1363   }
1364   // Keep the width spacing correct if things go wrong...
1365   if (width > 0)
1366     strm.Printf("%-*s", width, "");
1367 }
1368 
1369 static size_t DumpModuleObjfileHeaders(Stream &strm, ModuleList &module_list) {
1370   size_t num_dumped = 0;
1371   std::lock_guard<std::recursive_mutex> guard(module_list.GetMutex());
1372   const size_t num_modules = module_list.GetSize();
1373   if (num_modules > 0) {
1374     strm.Printf("Dumping headers for %" PRIu64 " module(s).\n",
1375                 static_cast<uint64_t>(num_modules));
1376     strm.IndentMore();
1377     for (size_t image_idx = 0; image_idx < num_modules; ++image_idx) {
1378       Module *module = module_list.GetModulePointerAtIndexUnlocked(image_idx);
1379       if (module) {
1380         if (num_dumped++ > 0) {
1381           strm.EOL();
1382           strm.EOL();
1383         }
1384         ObjectFile *objfile = module->GetObjectFile();
1385         objfile->Dump(&strm);
1386       }
1387     }
1388     strm.IndentLess();
1389   }
1390   return num_dumped;
1391 }
1392 
1393 static void DumpModuleSymtab(CommandInterpreter &interpreter, Stream &strm,
1394                              Module *module, SortOrder sort_order) {
1395   if (module) {
1396     SymbolVendor *sym_vendor = module->GetSymbolVendor();
1397     if (sym_vendor) {
1398       Symtab *symtab = sym_vendor->GetSymtab();
1399       if (symtab)
1400         symtab->Dump(&strm, interpreter.GetExecutionContext().GetTargetPtr(),
1401                      sort_order);
1402     }
1403   }
1404 }
1405 
1406 static void DumpModuleSections(CommandInterpreter &interpreter, Stream &strm,
1407                                Module *module) {
1408   if (module) {
1409     SectionList *section_list = module->GetSectionList();
1410     if (section_list) {
1411       strm.Printf("Sections for '%s' (%s):\n",
1412                   module->GetSpecificationDescription().c_str(),
1413                   module->GetArchitecture().GetArchitectureName());
1414       strm.IndentMore();
1415       section_list->Dump(&strm,
1416                          interpreter.GetExecutionContext().GetTargetPtr(), true,
1417                          UINT32_MAX);
1418       strm.IndentLess();
1419     }
1420   }
1421 }
1422 
1423 static bool DumpModuleSymbolVendor(Stream &strm, Module *module) {
1424   if (module) {
1425     SymbolVendor *symbol_vendor = module->GetSymbolVendor(true);
1426     if (symbol_vendor) {
1427       symbol_vendor->Dump(&strm);
1428       return true;
1429     }
1430   }
1431   return false;
1432 }
1433 
1434 static void DumpAddress(ExecutionContextScope *exe_scope,
1435                         const Address &so_addr, bool verbose, Stream &strm) {
1436   strm.IndentMore();
1437   strm.Indent("    Address: ");
1438   so_addr.Dump(&strm, exe_scope, Address::DumpStyleModuleWithFileAddress);
1439   strm.PutCString(" (");
1440   so_addr.Dump(&strm, exe_scope, Address::DumpStyleSectionNameOffset);
1441   strm.PutCString(")\n");
1442   strm.Indent("    Summary: ");
1443   const uint32_t save_indent = strm.GetIndentLevel();
1444   strm.SetIndentLevel(save_indent + 13);
1445   so_addr.Dump(&strm, exe_scope, Address::DumpStyleResolvedDescription);
1446   strm.SetIndentLevel(save_indent);
1447   // Print out detailed address information when verbose is enabled
1448   if (verbose) {
1449     strm.EOL();
1450     so_addr.Dump(&strm, exe_scope, Address::DumpStyleDetailedSymbolContext);
1451   }
1452   strm.IndentLess();
1453 }
1454 
1455 static bool LookupAddressInModule(CommandInterpreter &interpreter, Stream &strm,
1456                                   Module *module, uint32_t resolve_mask,
1457                                   lldb::addr_t raw_addr, lldb::addr_t offset,
1458                                   bool verbose) {
1459   if (module) {
1460     lldb::addr_t addr = raw_addr - offset;
1461     Address so_addr;
1462     SymbolContext sc;
1463     Target *target = interpreter.GetExecutionContext().GetTargetPtr();
1464     if (target && !target->GetSectionLoadList().IsEmpty()) {
1465       if (!target->GetSectionLoadList().ResolveLoadAddress(addr, so_addr))
1466         return false;
1467       else if (so_addr.GetModule().get() != module)
1468         return false;
1469     } else {
1470       if (!module->ResolveFileAddress(addr, so_addr))
1471         return false;
1472     }
1473 
1474     ExecutionContextScope *exe_scope =
1475         interpreter.GetExecutionContext().GetBestExecutionContextScope();
1476     DumpAddress(exe_scope, so_addr, verbose, strm);
1477     //        strm.IndentMore();
1478     //        strm.Indent ("    Address: ");
1479     //        so_addr.Dump (&strm, exe_scope,
1480     //        Address::DumpStyleModuleWithFileAddress);
1481     //        strm.PutCString (" (");
1482     //        so_addr.Dump (&strm, exe_scope,
1483     //        Address::DumpStyleSectionNameOffset);
1484     //        strm.PutCString (")\n");
1485     //        strm.Indent ("    Summary: ");
1486     //        const uint32_t save_indent = strm.GetIndentLevel ();
1487     //        strm.SetIndentLevel (save_indent + 13);
1488     //        so_addr.Dump (&strm, exe_scope,
1489     //        Address::DumpStyleResolvedDescription);
1490     //        strm.SetIndentLevel (save_indent);
1491     //        // Print out detailed address information when verbose is enabled
1492     //        if (verbose)
1493     //        {
1494     //            strm.EOL();
1495     //            so_addr.Dump (&strm, exe_scope,
1496     //            Address::DumpStyleDetailedSymbolContext);
1497     //        }
1498     //        strm.IndentLess();
1499     return true;
1500   }
1501 
1502   return false;
1503 }
1504 
1505 static uint32_t LookupSymbolInModule(CommandInterpreter &interpreter,
1506                                      Stream &strm, Module *module,
1507                                      const char *name, bool name_is_regex,
1508                                      bool verbose) {
1509   if (module) {
1510     SymbolContext sc;
1511 
1512     SymbolVendor *sym_vendor = module->GetSymbolVendor();
1513     if (sym_vendor) {
1514       Symtab *symtab = sym_vendor->GetSymtab();
1515       if (symtab) {
1516         std::vector<uint32_t> match_indexes;
1517         ConstString symbol_name(name);
1518         uint32_t num_matches = 0;
1519         if (name_is_regex) {
1520           RegularExpression name_regexp(name);
1521           num_matches = symtab->AppendSymbolIndexesMatchingRegExAndType(
1522               name_regexp, eSymbolTypeAny, match_indexes);
1523         } else {
1524           num_matches =
1525               symtab->AppendSymbolIndexesWithName(symbol_name, match_indexes);
1526         }
1527 
1528         if (num_matches > 0) {
1529           strm.Indent();
1530           strm.Printf("%u symbols match %s'%s' in ", num_matches,
1531                       name_is_regex ? "the regular expression " : "", name);
1532           DumpFullpath(strm, &module->GetFileSpec(), 0);
1533           strm.PutCString(":\n");
1534           strm.IndentMore();
1535           for (uint32_t i = 0; i < num_matches; ++i) {
1536             Symbol *symbol = symtab->SymbolAtIndex(match_indexes[i]);
1537             if (symbol && symbol->ValueIsAddress()) {
1538               DumpAddress(interpreter.GetExecutionContext()
1539                               .GetBestExecutionContextScope(),
1540                           symbol->GetAddressRef(), verbose, strm);
1541             }
1542           }
1543           strm.IndentLess();
1544           return num_matches;
1545         }
1546       }
1547     }
1548   }
1549   return 0;
1550 }
1551 
1552 static void DumpSymbolContextList(ExecutionContextScope *exe_scope,
1553                                   Stream &strm, SymbolContextList &sc_list,
1554                                   bool verbose) {
1555   strm.IndentMore();
1556 
1557   const uint32_t num_matches = sc_list.GetSize();
1558 
1559   for (uint32_t i = 0; i < num_matches; ++i) {
1560     SymbolContext sc;
1561     if (sc_list.GetContextAtIndex(i, sc)) {
1562       AddressRange range;
1563 
1564       sc.GetAddressRange(eSymbolContextEverything, 0, true, range);
1565 
1566       DumpAddress(exe_scope, range.GetBaseAddress(), verbose, strm);
1567     }
1568   }
1569   strm.IndentLess();
1570 }
1571 
1572 static size_t LookupFunctionInModule(CommandInterpreter &interpreter,
1573                                      Stream &strm, Module *module,
1574                                      const char *name, bool name_is_regex,
1575                                      bool include_inlines, bool include_symbols,
1576                                      bool verbose) {
1577   if (module && name && name[0]) {
1578     SymbolContextList sc_list;
1579     const bool append = true;
1580     size_t num_matches = 0;
1581     if (name_is_regex) {
1582       RegularExpression function_name_regex(name);
1583       num_matches = module->FindFunctions(function_name_regex, include_symbols,
1584                                           include_inlines, append, sc_list);
1585     } else {
1586       ConstString function_name(name);
1587       num_matches = module->FindFunctions(
1588           function_name, nullptr, eFunctionNameTypeAuto, include_symbols,
1589           include_inlines, append, sc_list);
1590     }
1591 
1592     if (num_matches) {
1593       strm.Indent();
1594       strm.Printf("%" PRIu64 " match%s found in ", (uint64_t)num_matches,
1595                   num_matches > 1 ? "es" : "");
1596       DumpFullpath(strm, &module->GetFileSpec(), 0);
1597       strm.PutCString(":\n");
1598       DumpSymbolContextList(
1599           interpreter.GetExecutionContext().GetBestExecutionContextScope(),
1600           strm, sc_list, verbose);
1601     }
1602     return num_matches;
1603   }
1604   return 0;
1605 }
1606 
1607 static size_t LookupTypeInModule(CommandInterpreter &interpreter, Stream &strm,
1608                                  Module *module, const char *name_cstr,
1609                                  bool name_is_regex) {
1610   if (module && name_cstr && name_cstr[0]) {
1611     TypeList type_list;
1612     const uint32_t max_num_matches = UINT32_MAX;
1613     size_t num_matches = 0;
1614     bool name_is_fully_qualified = false;
1615     SymbolContext sc;
1616 
1617     ConstString name(name_cstr);
1618     llvm::DenseSet<lldb_private::SymbolFile *> searched_symbol_files;
1619     num_matches =
1620         module->FindTypes(sc, name, name_is_fully_qualified, max_num_matches,
1621                           searched_symbol_files, type_list);
1622 
1623     if (num_matches) {
1624       strm.Indent();
1625       strm.Printf("%" PRIu64 " match%s found in ", (uint64_t)num_matches,
1626                   num_matches > 1 ? "es" : "");
1627       DumpFullpath(strm, &module->GetFileSpec(), 0);
1628       strm.PutCString(":\n");
1629       for (TypeSP type_sp : type_list.Types()) {
1630         if (type_sp) {
1631           // Resolve the clang type so that any forward references
1632           // to types that haven't yet been parsed will get parsed.
1633           type_sp->GetFullCompilerType();
1634           type_sp->GetDescription(&strm, eDescriptionLevelFull, true);
1635           // Print all typedef chains
1636           TypeSP typedef_type_sp(type_sp);
1637           TypeSP typedefed_type_sp(typedef_type_sp->GetTypedefType());
1638           while (typedefed_type_sp) {
1639             strm.EOL();
1640             strm.Printf("     typedef '%s': ",
1641                         typedef_type_sp->GetName().GetCString());
1642             typedefed_type_sp->GetFullCompilerType();
1643             typedefed_type_sp->GetDescription(&strm, eDescriptionLevelFull,
1644                                               true);
1645             typedef_type_sp = typedefed_type_sp;
1646             typedefed_type_sp = typedef_type_sp->GetTypedefType();
1647           }
1648         }
1649         strm.EOL();
1650       }
1651     }
1652     return num_matches;
1653   }
1654   return 0;
1655 }
1656 
1657 static size_t LookupTypeHere(CommandInterpreter &interpreter, Stream &strm,
1658                              const SymbolContext &sym_ctx,
1659                              const char *name_cstr, bool name_is_regex) {
1660   if (!sym_ctx.module_sp)
1661     return 0;
1662 
1663   TypeList type_list;
1664   const uint32_t max_num_matches = UINT32_MAX;
1665   size_t num_matches = 1;
1666   bool name_is_fully_qualified = false;
1667 
1668   ConstString name(name_cstr);
1669   llvm::DenseSet<SymbolFile *> searched_symbol_files;
1670   num_matches = sym_ctx.module_sp->FindTypes(
1671       sym_ctx, name, name_is_fully_qualified, max_num_matches,
1672       searched_symbol_files, type_list);
1673 
1674   if (num_matches) {
1675     strm.Indent();
1676     strm.PutCString("Best match found in ");
1677     DumpFullpath(strm, &sym_ctx.module_sp->GetFileSpec(), 0);
1678     strm.PutCString(":\n");
1679 
1680     TypeSP type_sp(type_list.GetTypeAtIndex(0));
1681     if (type_sp) {
1682       // Resolve the clang type so that any forward references
1683       // to types that haven't yet been parsed will get parsed.
1684       type_sp->GetFullCompilerType();
1685       type_sp->GetDescription(&strm, eDescriptionLevelFull, true);
1686       // Print all typedef chains
1687       TypeSP typedef_type_sp(type_sp);
1688       TypeSP typedefed_type_sp(typedef_type_sp->GetTypedefType());
1689       while (typedefed_type_sp) {
1690         strm.EOL();
1691         strm.Printf("     typedef '%s': ",
1692                     typedef_type_sp->GetName().GetCString());
1693         typedefed_type_sp->GetFullCompilerType();
1694         typedefed_type_sp->GetDescription(&strm, eDescriptionLevelFull, true);
1695         typedef_type_sp = typedefed_type_sp;
1696         typedefed_type_sp = typedef_type_sp->GetTypedefType();
1697       }
1698     }
1699     strm.EOL();
1700   }
1701   return num_matches;
1702 }
1703 
1704 static uint32_t LookupFileAndLineInModule(CommandInterpreter &interpreter,
1705                                           Stream &strm, Module *module,
1706                                           const FileSpec &file_spec,
1707                                           uint32_t line, bool check_inlines,
1708                                           bool verbose) {
1709   if (module && file_spec) {
1710     SymbolContextList sc_list;
1711     const uint32_t num_matches = module->ResolveSymbolContextsForFileSpec(
1712         file_spec, line, check_inlines, eSymbolContextEverything, sc_list);
1713     if (num_matches > 0) {
1714       strm.Indent();
1715       strm.Printf("%u match%s found in ", num_matches,
1716                   num_matches > 1 ? "es" : "");
1717       strm << file_spec;
1718       if (line > 0)
1719         strm.Printf(":%u", line);
1720       strm << " in ";
1721       DumpFullpath(strm, &module->GetFileSpec(), 0);
1722       strm.PutCString(":\n");
1723       DumpSymbolContextList(
1724           interpreter.GetExecutionContext().GetBestExecutionContextScope(),
1725           strm, sc_list, verbose);
1726       return num_matches;
1727     }
1728   }
1729   return 0;
1730 }
1731 
1732 static size_t FindModulesByName(Target *target, const char *module_name,
1733                                 ModuleList &module_list,
1734                                 bool check_global_list) {
1735   FileSpec module_file_spec(module_name, false);
1736   ModuleSpec module_spec(module_file_spec);
1737 
1738   const size_t initial_size = module_list.GetSize();
1739 
1740   if (check_global_list) {
1741     // Check the global list
1742     std::lock_guard<std::recursive_mutex> guard(
1743         Module::GetAllocationModuleCollectionMutex());
1744     const size_t num_modules = Module::GetNumberAllocatedModules();
1745     ModuleSP module_sp;
1746     for (size_t image_idx = 0; image_idx < num_modules; ++image_idx) {
1747       Module *module = Module::GetAllocatedModuleAtIndex(image_idx);
1748 
1749       if (module) {
1750         if (module->MatchesModuleSpec(module_spec)) {
1751           module_sp = module->shared_from_this();
1752           module_list.AppendIfNeeded(module_sp);
1753         }
1754       }
1755     }
1756   } else {
1757     if (target) {
1758       const size_t num_matches =
1759           target->GetImages().FindModules(module_spec, module_list);
1760 
1761       // Not found in our module list for our target, check the main
1762       // shared module list in case it is a extra file used somewhere
1763       // else
1764       if (num_matches == 0) {
1765         module_spec.GetArchitecture() = target->GetArchitecture();
1766         ModuleList::FindSharedModules(module_spec, module_list);
1767       }
1768     } else {
1769       ModuleList::FindSharedModules(module_spec, module_list);
1770     }
1771   }
1772 
1773   return module_list.GetSize() - initial_size;
1774 }
1775 
1776 #pragma mark CommandObjectTargetModulesModuleAutoComplete
1777 
1778 //----------------------------------------------------------------------
1779 // A base command object class that can auto complete with module file
1780 // paths
1781 //----------------------------------------------------------------------
1782 
1783 class CommandObjectTargetModulesModuleAutoComplete
1784     : public CommandObjectParsed {
1785 public:
1786   CommandObjectTargetModulesModuleAutoComplete(CommandInterpreter &interpreter,
1787                                                const char *name,
1788                                                const char *help,
1789                                                const char *syntax)
1790       : CommandObjectParsed(interpreter, name, help, syntax) {
1791     CommandArgumentEntry arg;
1792     CommandArgumentData file_arg;
1793 
1794     // Define the first (and only) variant of this arg.
1795     file_arg.arg_type = eArgTypeFilename;
1796     file_arg.arg_repetition = eArgRepeatStar;
1797 
1798     // There is only one variant this argument could be; put it into the
1799     // argument entry.
1800     arg.push_back(file_arg);
1801 
1802     // Push the data for the first argument into the m_arguments vector.
1803     m_arguments.push_back(arg);
1804   }
1805 
1806   ~CommandObjectTargetModulesModuleAutoComplete() override = default;
1807 
1808   int HandleArgumentCompletion(Args &input, int &cursor_index,
1809                                int &cursor_char_position,
1810                                OptionElementVector &opt_element_vector,
1811                                int match_start_point, int max_return_elements,
1812                                bool &word_complete,
1813                                StringList &matches) override {
1814     // Arguments are the standard module completer.
1815     std::string completion_str(input.GetArgumentAtIndex(cursor_index));
1816     completion_str.erase(cursor_char_position);
1817 
1818     CommandCompletions::InvokeCommonCompletionCallbacks(
1819         GetCommandInterpreter(), CommandCompletions::eModuleCompletion,
1820         completion_str.c_str(), match_start_point, max_return_elements, nullptr,
1821         word_complete, matches);
1822     return matches.GetSize();
1823   }
1824 };
1825 
1826 #pragma mark CommandObjectTargetModulesSourceFileAutoComplete
1827 
1828 //----------------------------------------------------------------------
1829 // A base command object class that can auto complete with module source
1830 // file paths
1831 //----------------------------------------------------------------------
1832 
1833 class CommandObjectTargetModulesSourceFileAutoComplete
1834     : public CommandObjectParsed {
1835 public:
1836   CommandObjectTargetModulesSourceFileAutoComplete(
1837       CommandInterpreter &interpreter, const char *name, const char *help,
1838       const char *syntax, uint32_t flags)
1839       : CommandObjectParsed(interpreter, name, help, syntax, flags) {
1840     CommandArgumentEntry arg;
1841     CommandArgumentData source_file_arg;
1842 
1843     // Define the first (and only) variant of this arg.
1844     source_file_arg.arg_type = eArgTypeSourceFile;
1845     source_file_arg.arg_repetition = eArgRepeatPlus;
1846 
1847     // There is only one variant this argument could be; put it into the
1848     // argument entry.
1849     arg.push_back(source_file_arg);
1850 
1851     // Push the data for the first argument into the m_arguments vector.
1852     m_arguments.push_back(arg);
1853   }
1854 
1855   ~CommandObjectTargetModulesSourceFileAutoComplete() override = default;
1856 
1857   int HandleArgumentCompletion(Args &input, int &cursor_index,
1858                                int &cursor_char_position,
1859                                OptionElementVector &opt_element_vector,
1860                                int match_start_point, int max_return_elements,
1861                                bool &word_complete,
1862                                StringList &matches) override {
1863     // Arguments are the standard source file completer.
1864     std::string completion_str(input.GetArgumentAtIndex(cursor_index));
1865     completion_str.erase(cursor_char_position);
1866 
1867     CommandCompletions::InvokeCommonCompletionCallbacks(
1868         GetCommandInterpreter(), CommandCompletions::eSourceFileCompletion,
1869         completion_str.c_str(), match_start_point, max_return_elements, nullptr,
1870         word_complete, matches);
1871     return matches.GetSize();
1872   }
1873 };
1874 
1875 #pragma mark CommandObjectTargetModulesDumpObjfile
1876 
1877 class CommandObjectTargetModulesDumpObjfile
1878     : public CommandObjectTargetModulesModuleAutoComplete {
1879 public:
1880   CommandObjectTargetModulesDumpObjfile(CommandInterpreter &interpreter)
1881       : CommandObjectTargetModulesModuleAutoComplete(
1882             interpreter, "target modules dump objfile",
1883             "Dump the object file headers from one or more target modules.",
1884             nullptr) {}
1885 
1886   ~CommandObjectTargetModulesDumpObjfile() override = default;
1887 
1888 protected:
1889   bool DoExecute(Args &command, CommandReturnObject &result) override {
1890     Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
1891     if (target == nullptr) {
1892       result.AppendError("invalid target, create a debug target using the "
1893                          "'target create' command");
1894       result.SetStatus(eReturnStatusFailed);
1895       return false;
1896     }
1897 
1898     uint32_t addr_byte_size = target->GetArchitecture().GetAddressByteSize();
1899     result.GetOutputStream().SetAddressByteSize(addr_byte_size);
1900     result.GetErrorStream().SetAddressByteSize(addr_byte_size);
1901 
1902     size_t num_dumped = 0;
1903     if (command.GetArgumentCount() == 0) {
1904       // Dump all headers for all modules images
1905       num_dumped = DumpModuleObjfileHeaders(result.GetOutputStream(),
1906                                             target->GetImages());
1907       if (num_dumped == 0) {
1908         result.AppendError("the target has no associated executable images");
1909         result.SetStatus(eReturnStatusFailed);
1910       }
1911     } else {
1912       // Find the modules that match the basename or full path.
1913       ModuleList module_list;
1914       const char *arg_cstr;
1915       for (int arg_idx = 0;
1916            (arg_cstr = command.GetArgumentAtIndex(arg_idx)) != nullptr;
1917            ++arg_idx) {
1918         size_t num_matched =
1919             FindModulesByName(target, arg_cstr, module_list, true);
1920         if (num_matched == 0) {
1921           result.AppendWarningWithFormat(
1922               "Unable to find an image that matches '%s'.\n", arg_cstr);
1923         }
1924       }
1925       // Dump all the modules we found.
1926       num_dumped =
1927           DumpModuleObjfileHeaders(result.GetOutputStream(), module_list);
1928     }
1929 
1930     if (num_dumped > 0) {
1931       result.SetStatus(eReturnStatusSuccessFinishResult);
1932     } else {
1933       result.AppendError("no matching executable images found");
1934       result.SetStatus(eReturnStatusFailed);
1935     }
1936     return result.Succeeded();
1937   }
1938 };
1939 
1940 #pragma mark CommandObjectTargetModulesDumpSymtab
1941 
1942 class CommandObjectTargetModulesDumpSymtab
1943     : public CommandObjectTargetModulesModuleAutoComplete {
1944 public:
1945   CommandObjectTargetModulesDumpSymtab(CommandInterpreter &interpreter)
1946       : CommandObjectTargetModulesModuleAutoComplete(
1947             interpreter, "target modules dump symtab",
1948             "Dump the symbol table from one or more target modules.", nullptr),
1949         m_options() {}
1950 
1951   ~CommandObjectTargetModulesDumpSymtab() override = default;
1952 
1953   Options *GetOptions() override { return &m_options; }
1954 
1955   class CommandOptions : public Options {
1956   public:
1957     CommandOptions() : Options(), m_sort_order(eSortOrderNone) {}
1958 
1959     ~CommandOptions() override = default;
1960 
1961     Error SetOptionValue(uint32_t option_idx, const char *option_arg,
1962                          ExecutionContext *execution_context) override {
1963       Error error;
1964       const int short_option = m_getopt_table[option_idx].val;
1965 
1966       switch (short_option) {
1967       case 's':
1968         m_sort_order = (SortOrder)Args::StringToOptionEnum(
1969             option_arg, g_option_table[option_idx].enum_values, eSortOrderNone,
1970             error);
1971         break;
1972 
1973       default:
1974         error.SetErrorStringWithFormat("invalid short option character '%c'",
1975                                        short_option);
1976         break;
1977       }
1978       return error;
1979     }
1980 
1981     void OptionParsingStarting(ExecutionContext *execution_context) override {
1982       m_sort_order = eSortOrderNone;
1983     }
1984 
1985     const OptionDefinition *GetDefinitions() override { return g_option_table; }
1986 
1987     // Options table: Required for subclasses of Options.
1988     static OptionDefinition g_option_table[];
1989 
1990     SortOrder m_sort_order;
1991   };
1992 
1993 protected:
1994   bool DoExecute(Args &command, CommandReturnObject &result) override {
1995     Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
1996     if (target == nullptr) {
1997       result.AppendError("invalid target, create a debug target using the "
1998                          "'target create' command");
1999       result.SetStatus(eReturnStatusFailed);
2000       return false;
2001     } else {
2002       uint32_t num_dumped = 0;
2003 
2004       uint32_t addr_byte_size = target->GetArchitecture().GetAddressByteSize();
2005       result.GetOutputStream().SetAddressByteSize(addr_byte_size);
2006       result.GetErrorStream().SetAddressByteSize(addr_byte_size);
2007 
2008       if (command.GetArgumentCount() == 0) {
2009         // Dump all sections for all modules images
2010         std::lock_guard<std::recursive_mutex> guard(
2011             target->GetImages().GetMutex());
2012         const size_t num_modules = target->GetImages().GetSize();
2013         if (num_modules > 0) {
2014           result.GetOutputStream().Printf("Dumping symbol table for %" PRIu64
2015                                           " modules.\n",
2016                                           (uint64_t)num_modules);
2017           for (size_t image_idx = 0; image_idx < num_modules; ++image_idx) {
2018             if (num_dumped > 0) {
2019               result.GetOutputStream().EOL();
2020               result.GetOutputStream().EOL();
2021             }
2022             num_dumped++;
2023             DumpModuleSymtab(
2024                 m_interpreter, result.GetOutputStream(),
2025                 target->GetImages().GetModulePointerAtIndexUnlocked(image_idx),
2026                 m_options.m_sort_order);
2027           }
2028         } else {
2029           result.AppendError("the target has no associated executable images");
2030           result.SetStatus(eReturnStatusFailed);
2031           return false;
2032         }
2033       } else {
2034         // Dump specified images (by basename or fullpath)
2035         const char *arg_cstr;
2036         for (int arg_idx = 0;
2037              (arg_cstr = command.GetArgumentAtIndex(arg_idx)) != nullptr;
2038              ++arg_idx) {
2039           ModuleList module_list;
2040           const size_t num_matches =
2041               FindModulesByName(target, arg_cstr, module_list, true);
2042           if (num_matches > 0) {
2043             for (size_t i = 0; i < num_matches; ++i) {
2044               Module *module = module_list.GetModulePointerAtIndex(i);
2045               if (module) {
2046                 if (num_dumped > 0) {
2047                   result.GetOutputStream().EOL();
2048                   result.GetOutputStream().EOL();
2049                 }
2050                 num_dumped++;
2051                 DumpModuleSymtab(m_interpreter, result.GetOutputStream(),
2052                                  module, m_options.m_sort_order);
2053               }
2054             }
2055           } else
2056             result.AppendWarningWithFormat(
2057                 "Unable to find an image that matches '%s'.\n", arg_cstr);
2058         }
2059       }
2060 
2061       if (num_dumped > 0)
2062         result.SetStatus(eReturnStatusSuccessFinishResult);
2063       else {
2064         result.AppendError("no matching executable images found");
2065         result.SetStatus(eReturnStatusFailed);
2066       }
2067     }
2068     return result.Succeeded();
2069   }
2070 
2071   CommandOptions m_options;
2072 };
2073 
2074 static OptionEnumValueElement g_sort_option_enumeration[4] = {
2075     {eSortOrderNone, "none",
2076      "No sorting, use the original symbol table order."},
2077     {eSortOrderByAddress, "address", "Sort output by symbol address."},
2078     {eSortOrderByName, "name", "Sort output by symbol name."},
2079     {0, nullptr, nullptr}};
2080 
2081 OptionDefinition
2082     CommandObjectTargetModulesDumpSymtab::CommandOptions::g_option_table[] = {
2083         // clang-format off
2084   {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."},
2085   {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr}
2086         // clang-format on
2087 };
2088 
2089 #pragma mark CommandObjectTargetModulesDumpSections
2090 
2091 //----------------------------------------------------------------------
2092 // Image section dumping command
2093 //----------------------------------------------------------------------
2094 
2095 class CommandObjectTargetModulesDumpSections
2096     : public CommandObjectTargetModulesModuleAutoComplete {
2097 public:
2098   CommandObjectTargetModulesDumpSections(CommandInterpreter &interpreter)
2099       : CommandObjectTargetModulesModuleAutoComplete(
2100             interpreter, "target modules dump sections",
2101             "Dump the sections from one or more target modules.",
2102             //"target modules dump sections [<file1> ...]")
2103             nullptr) {}
2104 
2105   ~CommandObjectTargetModulesDumpSections() override = default;
2106 
2107 protected:
2108   bool DoExecute(Args &command, CommandReturnObject &result) override {
2109     Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
2110     if (target == nullptr) {
2111       result.AppendError("invalid target, create a debug target using the "
2112                          "'target create' command");
2113       result.SetStatus(eReturnStatusFailed);
2114       return false;
2115     } else {
2116       uint32_t num_dumped = 0;
2117 
2118       uint32_t addr_byte_size = target->GetArchitecture().GetAddressByteSize();
2119       result.GetOutputStream().SetAddressByteSize(addr_byte_size);
2120       result.GetErrorStream().SetAddressByteSize(addr_byte_size);
2121 
2122       if (command.GetArgumentCount() == 0) {
2123         // Dump all sections for all modules images
2124         const size_t num_modules = target->GetImages().GetSize();
2125         if (num_modules > 0) {
2126           result.GetOutputStream().Printf("Dumping sections for %" PRIu64
2127                                           " modules.\n",
2128                                           (uint64_t)num_modules);
2129           for (size_t image_idx = 0; image_idx < num_modules; ++image_idx) {
2130             num_dumped++;
2131             DumpModuleSections(
2132                 m_interpreter, result.GetOutputStream(),
2133                 target->GetImages().GetModulePointerAtIndex(image_idx));
2134           }
2135         } else {
2136           result.AppendError("the target has no associated executable images");
2137           result.SetStatus(eReturnStatusFailed);
2138           return false;
2139         }
2140       } else {
2141         // Dump specified images (by basename or fullpath)
2142         const char *arg_cstr;
2143         for (int arg_idx = 0;
2144              (arg_cstr = command.GetArgumentAtIndex(arg_idx)) != nullptr;
2145              ++arg_idx) {
2146           ModuleList module_list;
2147           const size_t num_matches =
2148               FindModulesByName(target, arg_cstr, module_list, true);
2149           if (num_matches > 0) {
2150             for (size_t i = 0; i < num_matches; ++i) {
2151               Module *module = module_list.GetModulePointerAtIndex(i);
2152               if (module) {
2153                 num_dumped++;
2154                 DumpModuleSections(m_interpreter, result.GetOutputStream(),
2155                                    module);
2156               }
2157             }
2158           } else {
2159             // Check the global list
2160             std::lock_guard<std::recursive_mutex> guard(
2161                 Module::GetAllocationModuleCollectionMutex());
2162 
2163             result.AppendWarningWithFormat(
2164                 "Unable to find an image that matches '%s'.\n", arg_cstr);
2165           }
2166         }
2167       }
2168 
2169       if (num_dumped > 0)
2170         result.SetStatus(eReturnStatusSuccessFinishResult);
2171       else {
2172         result.AppendError("no matching executable images found");
2173         result.SetStatus(eReturnStatusFailed);
2174       }
2175     }
2176     return result.Succeeded();
2177   }
2178 };
2179 
2180 #pragma mark CommandObjectTargetModulesDumpSymfile
2181 
2182 //----------------------------------------------------------------------
2183 // Image debug symbol dumping command
2184 //----------------------------------------------------------------------
2185 
2186 class CommandObjectTargetModulesDumpSymfile
2187     : public CommandObjectTargetModulesModuleAutoComplete {
2188 public:
2189   CommandObjectTargetModulesDumpSymfile(CommandInterpreter &interpreter)
2190       : CommandObjectTargetModulesModuleAutoComplete(
2191             interpreter, "target modules dump symfile",
2192             "Dump the debug symbol file for one or more target modules.",
2193             //"target modules dump symfile [<file1> ...]")
2194             nullptr) {}
2195 
2196   ~CommandObjectTargetModulesDumpSymfile() override = default;
2197 
2198 protected:
2199   bool DoExecute(Args &command, CommandReturnObject &result) override {
2200     Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
2201     if (target == nullptr) {
2202       result.AppendError("invalid target, create a debug target using the "
2203                          "'target create' command");
2204       result.SetStatus(eReturnStatusFailed);
2205       return false;
2206     } else {
2207       uint32_t num_dumped = 0;
2208 
2209       uint32_t addr_byte_size = target->GetArchitecture().GetAddressByteSize();
2210       result.GetOutputStream().SetAddressByteSize(addr_byte_size);
2211       result.GetErrorStream().SetAddressByteSize(addr_byte_size);
2212 
2213       if (command.GetArgumentCount() == 0) {
2214         // Dump all sections for all modules images
2215         const ModuleList &target_modules = target->GetImages();
2216         std::lock_guard<std::recursive_mutex> guard(target_modules.GetMutex());
2217         const size_t num_modules = target_modules.GetSize();
2218         if (num_modules > 0) {
2219           result.GetOutputStream().Printf("Dumping debug symbols for %" PRIu64
2220                                           " modules.\n",
2221                                           (uint64_t)num_modules);
2222           for (uint32_t image_idx = 0; image_idx < num_modules; ++image_idx) {
2223             if (DumpModuleSymbolVendor(
2224                     result.GetOutputStream(),
2225                     target_modules.GetModulePointerAtIndexUnlocked(image_idx)))
2226               num_dumped++;
2227           }
2228         } else {
2229           result.AppendError("the target has no associated executable images");
2230           result.SetStatus(eReturnStatusFailed);
2231           return false;
2232         }
2233       } else {
2234         // Dump specified images (by basename or fullpath)
2235         const char *arg_cstr;
2236         for (int arg_idx = 0;
2237              (arg_cstr = command.GetArgumentAtIndex(arg_idx)) != nullptr;
2238              ++arg_idx) {
2239           ModuleList module_list;
2240           const size_t num_matches =
2241               FindModulesByName(target, arg_cstr, module_list, true);
2242           if (num_matches > 0) {
2243             for (size_t i = 0; i < num_matches; ++i) {
2244               Module *module = module_list.GetModulePointerAtIndex(i);
2245               if (module) {
2246                 if (DumpModuleSymbolVendor(result.GetOutputStream(), module))
2247                   num_dumped++;
2248               }
2249             }
2250           } else
2251             result.AppendWarningWithFormat(
2252                 "Unable to find an image that matches '%s'.\n", arg_cstr);
2253         }
2254       }
2255 
2256       if (num_dumped > 0)
2257         result.SetStatus(eReturnStatusSuccessFinishResult);
2258       else {
2259         result.AppendError("no matching executable images found");
2260         result.SetStatus(eReturnStatusFailed);
2261       }
2262     }
2263     return result.Succeeded();
2264   }
2265 };
2266 
2267 #pragma mark CommandObjectTargetModulesDumpLineTable
2268 
2269 //----------------------------------------------------------------------
2270 // Image debug line table dumping command
2271 //----------------------------------------------------------------------
2272 
2273 class CommandObjectTargetModulesDumpLineTable
2274     : public CommandObjectTargetModulesSourceFileAutoComplete {
2275 public:
2276   CommandObjectTargetModulesDumpLineTable(CommandInterpreter &interpreter)
2277       : CommandObjectTargetModulesSourceFileAutoComplete(
2278             interpreter, "target modules dump line-table",
2279             "Dump the line table for one or more compilation units.", nullptr,
2280             eCommandRequiresTarget) {}
2281 
2282   ~CommandObjectTargetModulesDumpLineTable() override = default;
2283 
2284 protected:
2285   bool DoExecute(Args &command, CommandReturnObject &result) override {
2286     Target *target = m_exe_ctx.GetTargetPtr();
2287     uint32_t total_num_dumped = 0;
2288 
2289     uint32_t addr_byte_size = target->GetArchitecture().GetAddressByteSize();
2290     result.GetOutputStream().SetAddressByteSize(addr_byte_size);
2291     result.GetErrorStream().SetAddressByteSize(addr_byte_size);
2292 
2293     if (command.GetArgumentCount() == 0) {
2294       result.AppendError("file option must be specified.");
2295       result.SetStatus(eReturnStatusFailed);
2296       return result.Succeeded();
2297     } else {
2298       // Dump specified images (by basename or fullpath)
2299       const char *arg_cstr;
2300       for (int arg_idx = 0;
2301            (arg_cstr = command.GetArgumentAtIndex(arg_idx)) != nullptr;
2302            ++arg_idx) {
2303         FileSpec file_spec(arg_cstr, false);
2304 
2305         const ModuleList &target_modules = target->GetImages();
2306         std::lock_guard<std::recursive_mutex> guard(target_modules.GetMutex());
2307         const size_t num_modules = target_modules.GetSize();
2308         if (num_modules > 0) {
2309           uint32_t num_dumped = 0;
2310           for (uint32_t i = 0; i < num_modules; ++i) {
2311             if (DumpCompileUnitLineTable(
2312                     m_interpreter, result.GetOutputStream(),
2313                     target_modules.GetModulePointerAtIndexUnlocked(i),
2314                     file_spec, m_exe_ctx.GetProcessPtr() &&
2315                                    m_exe_ctx.GetProcessRef().IsAlive()))
2316               num_dumped++;
2317           }
2318           if (num_dumped == 0)
2319             result.AppendWarningWithFormat(
2320                 "No source filenames matched '%s'.\n", arg_cstr);
2321           else
2322             total_num_dumped += num_dumped;
2323         }
2324       }
2325     }
2326 
2327     if (total_num_dumped > 0)
2328       result.SetStatus(eReturnStatusSuccessFinishResult);
2329     else {
2330       result.AppendError("no source filenames matched any command arguments");
2331       result.SetStatus(eReturnStatusFailed);
2332     }
2333     return result.Succeeded();
2334   }
2335 };
2336 
2337 #pragma mark CommandObjectTargetModulesDump
2338 
2339 //----------------------------------------------------------------------
2340 // Dump multi-word command for target modules
2341 //----------------------------------------------------------------------
2342 
2343 class CommandObjectTargetModulesDump : public CommandObjectMultiword {
2344 public:
2345   //------------------------------------------------------------------
2346   // Constructors and Destructors
2347   //------------------------------------------------------------------
2348   CommandObjectTargetModulesDump(CommandInterpreter &interpreter)
2349       : CommandObjectMultiword(interpreter, "target modules dump",
2350                                "Commands for dumping information about one or "
2351                                "more target modules.",
2352                                "target modules dump "
2353                                "[headers|symtab|sections|symfile|line-table] "
2354                                "[<file1> <file2> ...]") {
2355     LoadSubCommand("objfile",
2356                    CommandObjectSP(
2357                        new CommandObjectTargetModulesDumpObjfile(interpreter)));
2358     LoadSubCommand(
2359         "symtab",
2360         CommandObjectSP(new CommandObjectTargetModulesDumpSymtab(interpreter)));
2361     LoadSubCommand("sections",
2362                    CommandObjectSP(new CommandObjectTargetModulesDumpSections(
2363                        interpreter)));
2364     LoadSubCommand("symfile",
2365                    CommandObjectSP(
2366                        new CommandObjectTargetModulesDumpSymfile(interpreter)));
2367     LoadSubCommand("line-table",
2368                    CommandObjectSP(new CommandObjectTargetModulesDumpLineTable(
2369                        interpreter)));
2370   }
2371 
2372   ~CommandObjectTargetModulesDump() override = default;
2373 };
2374 
2375 class CommandObjectTargetModulesAdd : public CommandObjectParsed {
2376 public:
2377   CommandObjectTargetModulesAdd(CommandInterpreter &interpreter)
2378       : CommandObjectParsed(interpreter, "target modules add",
2379                             "Add a new module to the current target's modules.",
2380                             "target modules add [<module>]"),
2381         m_option_group(),
2382         m_symbol_file(LLDB_OPT_SET_1, false, "symfile", 's', 0,
2383                       eArgTypeFilename, "Fullpath to a stand alone debug "
2384                                         "symbols file for when debug symbols "
2385                                         "are not in the executable.") {
2386     m_option_group.Append(&m_uuid_option_group, LLDB_OPT_SET_ALL,
2387                           LLDB_OPT_SET_1);
2388     m_option_group.Append(&m_symbol_file, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
2389     m_option_group.Finalize();
2390   }
2391 
2392   ~CommandObjectTargetModulesAdd() override = default;
2393 
2394   Options *GetOptions() override { return &m_option_group; }
2395 
2396   int HandleArgumentCompletion(Args &input, int &cursor_index,
2397                                int &cursor_char_position,
2398                                OptionElementVector &opt_element_vector,
2399                                int match_start_point, int max_return_elements,
2400                                bool &word_complete,
2401                                StringList &matches) override {
2402     std::string completion_str(input.GetArgumentAtIndex(cursor_index));
2403     completion_str.erase(cursor_char_position);
2404 
2405     CommandCompletions::InvokeCommonCompletionCallbacks(
2406         GetCommandInterpreter(), CommandCompletions::eDiskFileCompletion,
2407         completion_str.c_str(), match_start_point, max_return_elements, nullptr,
2408         word_complete, matches);
2409     return matches.GetSize();
2410   }
2411 
2412 protected:
2413   OptionGroupOptions m_option_group;
2414   OptionGroupUUID m_uuid_option_group;
2415   OptionGroupFile m_symbol_file;
2416 
2417   bool DoExecute(Args &args, CommandReturnObject &result) override {
2418     Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
2419     if (target == nullptr) {
2420       result.AppendError("invalid target, create a debug target using the "
2421                          "'target create' command");
2422       result.SetStatus(eReturnStatusFailed);
2423       return false;
2424     } else {
2425       bool flush = false;
2426 
2427       const size_t argc = args.GetArgumentCount();
2428       if (argc == 0) {
2429         if (m_uuid_option_group.GetOptionValue().OptionWasSet()) {
2430           // We are given a UUID only, go locate the file
2431           ModuleSpec module_spec;
2432           module_spec.GetUUID() =
2433               m_uuid_option_group.GetOptionValue().GetCurrentValue();
2434           if (m_symbol_file.GetOptionValue().OptionWasSet())
2435             module_spec.GetSymbolFileSpec() =
2436                 m_symbol_file.GetOptionValue().GetCurrentValue();
2437           if (Symbols::DownloadObjectAndSymbolFile(module_spec)) {
2438             ModuleSP module_sp(target->GetSharedModule(module_spec));
2439             if (module_sp) {
2440               result.SetStatus(eReturnStatusSuccessFinishResult);
2441               return true;
2442             } else {
2443               StreamString strm;
2444               module_spec.GetUUID().Dump(&strm);
2445               if (module_spec.GetFileSpec()) {
2446                 if (module_spec.GetSymbolFileSpec()) {
2447                   result.AppendErrorWithFormat(
2448                       "Unable to create the executable or symbol file with "
2449                       "UUID %s with path %s and symbol file %s",
2450                       strm.GetString().c_str(),
2451                       module_spec.GetFileSpec().GetPath().c_str(),
2452                       module_spec.GetSymbolFileSpec().GetPath().c_str());
2453                 } else {
2454                   result.AppendErrorWithFormat(
2455                       "Unable to create the executable or symbol file with "
2456                       "UUID %s with path %s",
2457                       strm.GetString().c_str(),
2458                       module_spec.GetFileSpec().GetPath().c_str());
2459                 }
2460               } else {
2461                 result.AppendErrorWithFormat("Unable to create the executable "
2462                                              "or symbol file with UUID %s",
2463                                              strm.GetString().c_str());
2464               }
2465               result.SetStatus(eReturnStatusFailed);
2466               return false;
2467             }
2468           } else {
2469             StreamString strm;
2470             module_spec.GetUUID().Dump(&strm);
2471             result.AppendErrorWithFormat(
2472                 "Unable to locate the executable or symbol file with UUID %s",
2473                 strm.GetString().c_str());
2474             result.SetStatus(eReturnStatusFailed);
2475             return false;
2476           }
2477         } else {
2478           result.AppendError(
2479               "one or more executable image paths must be specified");
2480           result.SetStatus(eReturnStatusFailed);
2481           return false;
2482         }
2483       } else {
2484         for (size_t i = 0; i < argc; ++i) {
2485           const char *path = args.GetArgumentAtIndex(i);
2486           if (path) {
2487             FileSpec file_spec(path, true);
2488             if (file_spec.Exists()) {
2489               ModuleSpec module_spec(file_spec);
2490               if (m_uuid_option_group.GetOptionValue().OptionWasSet())
2491                 module_spec.GetUUID() =
2492                     m_uuid_option_group.GetOptionValue().GetCurrentValue();
2493               if (m_symbol_file.GetOptionValue().OptionWasSet())
2494                 module_spec.GetSymbolFileSpec() =
2495                     m_symbol_file.GetOptionValue().GetCurrentValue();
2496               if (!module_spec.GetArchitecture().IsValid())
2497                 module_spec.GetArchitecture() = target->GetArchitecture();
2498               Error error;
2499               ModuleSP module_sp(target->GetSharedModule(module_spec, &error));
2500               if (!module_sp) {
2501                 const char *error_cstr = error.AsCString();
2502                 if (error_cstr)
2503                   result.AppendError(error_cstr);
2504                 else
2505                   result.AppendErrorWithFormat("unsupported module: %s", path);
2506                 result.SetStatus(eReturnStatusFailed);
2507                 return false;
2508               } else {
2509                 flush = true;
2510               }
2511               result.SetStatus(eReturnStatusSuccessFinishResult);
2512             } else {
2513               char resolved_path[PATH_MAX];
2514               result.SetStatus(eReturnStatusFailed);
2515               if (file_spec.GetPath(resolved_path, sizeof(resolved_path))) {
2516                 if (strcmp(resolved_path, path) != 0) {
2517                   result.AppendErrorWithFormat(
2518                       "invalid module path '%s' with resolved path '%s'\n",
2519                       path, resolved_path);
2520                   break;
2521                 }
2522               }
2523               result.AppendErrorWithFormat("invalid module path '%s'\n", path);
2524               break;
2525             }
2526           }
2527         }
2528       }
2529 
2530       if (flush) {
2531         ProcessSP process = target->GetProcessSP();
2532         if (process)
2533           process->Flush();
2534       }
2535     }
2536 
2537     return result.Succeeded();
2538   }
2539 };
2540 
2541 class CommandObjectTargetModulesLoad
2542     : public CommandObjectTargetModulesModuleAutoComplete {
2543 public:
2544   CommandObjectTargetModulesLoad(CommandInterpreter &interpreter)
2545       : CommandObjectTargetModulesModuleAutoComplete(
2546             interpreter, "target modules load", "Set the load addresses for "
2547                                                 "one or more sections in a "
2548                                                 "target module.",
2549             "target modules load [--file <module> --uuid <uuid>] <sect-name> "
2550             "<address> [<sect-name> <address> ....]"),
2551         m_option_group(),
2552         m_file_option(LLDB_OPT_SET_1, false, "file", 'f', 0, eArgTypeName,
2553                       "Fullpath or basename for module to load.", ""),
2554         m_slide_option(LLDB_OPT_SET_1, false, "slide", 's', 0, eArgTypeOffset,
2555                        "Set the load address for all sections to be the "
2556                        "virtual address in the file plus the offset.",
2557                        0) {
2558     m_option_group.Append(&m_uuid_option_group, LLDB_OPT_SET_ALL,
2559                           LLDB_OPT_SET_1);
2560     m_option_group.Append(&m_file_option, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
2561     m_option_group.Append(&m_slide_option, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
2562     m_option_group.Finalize();
2563   }
2564 
2565   ~CommandObjectTargetModulesLoad() override = default;
2566 
2567   Options *GetOptions() override { return &m_option_group; }
2568 
2569 protected:
2570   bool DoExecute(Args &args, CommandReturnObject &result) override {
2571     Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
2572     if (target == nullptr) {
2573       result.AppendError("invalid target, create a debug target using the "
2574                          "'target create' command");
2575       result.SetStatus(eReturnStatusFailed);
2576       return false;
2577     } else {
2578       const size_t argc = args.GetArgumentCount();
2579       ModuleSpec module_spec;
2580       bool search_using_module_spec = false;
2581       if (m_file_option.GetOptionValue().OptionWasSet()) {
2582         search_using_module_spec = true;
2583         const char *arg_cstr = m_file_option.GetOptionValue().GetCurrentValue();
2584         const bool use_global_module_list = true;
2585         ModuleList module_list;
2586         const size_t num_matches = FindModulesByName(
2587             target, arg_cstr, module_list, use_global_module_list);
2588         if (num_matches == 1) {
2589           module_spec.GetFileSpec() =
2590               module_list.GetModuleAtIndex(0)->GetFileSpec();
2591         } else if (num_matches > 1) {
2592           search_using_module_spec = false;
2593           result.AppendErrorWithFormat(
2594               "more than 1 module matched by name '%s'\n", arg_cstr);
2595           result.SetStatus(eReturnStatusFailed);
2596         } else {
2597           search_using_module_spec = false;
2598           result.AppendErrorWithFormat("no object file for module '%s'\n",
2599                                        arg_cstr);
2600           result.SetStatus(eReturnStatusFailed);
2601         }
2602       }
2603 
2604       if (m_uuid_option_group.GetOptionValue().OptionWasSet()) {
2605         search_using_module_spec = true;
2606         module_spec.GetUUID() =
2607             m_uuid_option_group.GetOptionValue().GetCurrentValue();
2608       }
2609 
2610       if (search_using_module_spec) {
2611         ModuleList matching_modules;
2612         const size_t num_matches =
2613             target->GetImages().FindModules(module_spec, matching_modules);
2614 
2615         char path[PATH_MAX];
2616         if (num_matches == 1) {
2617           Module *module = matching_modules.GetModulePointerAtIndex(0);
2618           if (module) {
2619             ObjectFile *objfile = module->GetObjectFile();
2620             if (objfile) {
2621               SectionList *section_list = module->GetSectionList();
2622               if (section_list) {
2623                 bool changed = false;
2624                 if (argc == 0) {
2625                   if (m_slide_option.GetOptionValue().OptionWasSet()) {
2626                     const addr_t slide =
2627                         m_slide_option.GetOptionValue().GetCurrentValue();
2628                     const bool slide_is_offset = true;
2629                     module->SetLoadAddress(*target, slide, slide_is_offset,
2630                                            changed);
2631                   } else {
2632                     result.AppendError("one or more section name + load "
2633                                        "address pair must be specified");
2634                     result.SetStatus(eReturnStatusFailed);
2635                     return false;
2636                   }
2637                 } else {
2638                   if (m_slide_option.GetOptionValue().OptionWasSet()) {
2639                     result.AppendError("The \"--slide <offset>\" option can't "
2640                                        "be used in conjunction with setting "
2641                                        "section load addresses.\n");
2642                     result.SetStatus(eReturnStatusFailed);
2643                     return false;
2644                   }
2645 
2646                   for (size_t i = 0; i < argc; i += 2) {
2647                     const char *sect_name = args.GetArgumentAtIndex(i);
2648                     const char *load_addr_cstr = args.GetArgumentAtIndex(i + 1);
2649                     if (sect_name && load_addr_cstr) {
2650                       ConstString const_sect_name(sect_name);
2651                       bool success = false;
2652                       addr_t load_addr = StringConvert::ToUInt64(
2653                           load_addr_cstr, LLDB_INVALID_ADDRESS, 0, &success);
2654                       if (success) {
2655                         SectionSP section_sp(
2656                             section_list->FindSectionByName(const_sect_name));
2657                         if (section_sp) {
2658                           if (section_sp->IsThreadSpecific()) {
2659                             result.AppendErrorWithFormat(
2660                                 "thread specific sections are not yet "
2661                                 "supported (section '%s')\n",
2662                                 sect_name);
2663                             result.SetStatus(eReturnStatusFailed);
2664                             break;
2665                           } else {
2666                             if (target->GetSectionLoadList()
2667                                     .SetSectionLoadAddress(section_sp,
2668                                                            load_addr))
2669                               changed = true;
2670                             result.AppendMessageWithFormat(
2671                                 "section '%s' loaded at 0x%" PRIx64 "\n",
2672                                 sect_name, load_addr);
2673                           }
2674                         } else {
2675                           result.AppendErrorWithFormat("no section found that "
2676                                                        "matches the section "
2677                                                        "name '%s'\n",
2678                                                        sect_name);
2679                           result.SetStatus(eReturnStatusFailed);
2680                           break;
2681                         }
2682                       } else {
2683                         result.AppendErrorWithFormat(
2684                             "invalid load address string '%s'\n",
2685                             load_addr_cstr);
2686                         result.SetStatus(eReturnStatusFailed);
2687                         break;
2688                       }
2689                     } else {
2690                       if (sect_name)
2691                         result.AppendError("section names must be followed by "
2692                                            "a load address.\n");
2693                       else
2694                         result.AppendError("one or more section name + load "
2695                                            "address pair must be specified.\n");
2696                       result.SetStatus(eReturnStatusFailed);
2697                       break;
2698                     }
2699                   }
2700                 }
2701 
2702                 if (changed) {
2703                   target->ModulesDidLoad(matching_modules);
2704                   Process *process = m_exe_ctx.GetProcessPtr();
2705                   if (process)
2706                     process->Flush();
2707                 }
2708               } else {
2709                 module->GetFileSpec().GetPath(path, sizeof(path));
2710                 result.AppendErrorWithFormat(
2711                     "no sections in object file '%s'\n", path);
2712                 result.SetStatus(eReturnStatusFailed);
2713               }
2714             } else {
2715               module->GetFileSpec().GetPath(path, sizeof(path));
2716               result.AppendErrorWithFormat("no object file for module '%s'\n",
2717                                            path);
2718               result.SetStatus(eReturnStatusFailed);
2719             }
2720           } else {
2721             FileSpec *module_spec_file = module_spec.GetFileSpecPtr();
2722             if (module_spec_file) {
2723               module_spec_file->GetPath(path, sizeof(path));
2724               result.AppendErrorWithFormat("invalid module '%s'.\n", path);
2725             } else
2726               result.AppendError("no module spec");
2727             result.SetStatus(eReturnStatusFailed);
2728           }
2729         } else {
2730           std::string uuid_str;
2731 
2732           if (module_spec.GetFileSpec())
2733             module_spec.GetFileSpec().GetPath(path, sizeof(path));
2734           else
2735             path[0] = '\0';
2736 
2737           if (module_spec.GetUUIDPtr())
2738             uuid_str = module_spec.GetUUID().GetAsString();
2739           if (num_matches > 1) {
2740             result.AppendErrorWithFormat(
2741                 "multiple modules match%s%s%s%s:\n", path[0] ? " file=" : "",
2742                 path, !uuid_str.empty() ? " uuid=" : "", uuid_str.c_str());
2743             for (size_t i = 0; i < num_matches; ++i) {
2744               if (matching_modules.GetModulePointerAtIndex(i)
2745                       ->GetFileSpec()
2746                       .GetPath(path, sizeof(path)))
2747                 result.AppendMessageWithFormat("%s\n", path);
2748             }
2749           } else {
2750             result.AppendErrorWithFormat(
2751                 "no modules were found  that match%s%s%s%s.\n",
2752                 path[0] ? " file=" : "", path,
2753                 !uuid_str.empty() ? " uuid=" : "", uuid_str.c_str());
2754           }
2755           result.SetStatus(eReturnStatusFailed);
2756         }
2757       } else {
2758         result.AppendError("either the \"--file <module>\" or the \"--uuid "
2759                            "<uuid>\" option must be specified.\n");
2760         result.SetStatus(eReturnStatusFailed);
2761         return false;
2762       }
2763     }
2764     return result.Succeeded();
2765   }
2766 
2767   OptionGroupOptions m_option_group;
2768   OptionGroupUUID m_uuid_option_group;
2769   OptionGroupString m_file_option;
2770   OptionGroupUInt64 m_slide_option;
2771 };
2772 
2773 //----------------------------------------------------------------------
2774 // List images with associated information
2775 //----------------------------------------------------------------------
2776 class CommandObjectTargetModulesList : public CommandObjectParsed {
2777 public:
2778   class CommandOptions : public Options {
2779   public:
2780     CommandOptions()
2781         : Options(), m_format_array(), m_use_global_module_list(false),
2782           m_module_addr(LLDB_INVALID_ADDRESS) {}
2783 
2784     ~CommandOptions() override = default;
2785 
2786     Error SetOptionValue(uint32_t option_idx, const char *option_arg,
2787                          ExecutionContext *execution_context) override {
2788       Error error;
2789 
2790       const int short_option = m_getopt_table[option_idx].val;
2791       if (short_option == 'g') {
2792         m_use_global_module_list = true;
2793       } else if (short_option == 'a') {
2794         m_module_addr = Args::StringToAddress(execution_context, option_arg,
2795                                               LLDB_INVALID_ADDRESS, &error);
2796       } else {
2797         unsigned long width = 0;
2798         if (option_arg)
2799           width = strtoul(option_arg, nullptr, 0);
2800         m_format_array.push_back(std::make_pair(short_option, width));
2801       }
2802       return error;
2803     }
2804 
2805     void OptionParsingStarting(ExecutionContext *execution_context) override {
2806       m_format_array.clear();
2807       m_use_global_module_list = false;
2808       m_module_addr = LLDB_INVALID_ADDRESS;
2809     }
2810 
2811     const OptionDefinition *GetDefinitions() override { return g_option_table; }
2812 
2813     // Options table: Required for subclasses of Options.
2814 
2815     static OptionDefinition g_option_table[];
2816 
2817     // Instance variables to hold the values for command options.
2818     typedef std::vector<std::pair<char, uint32_t>> FormatWidthCollection;
2819     FormatWidthCollection m_format_array;
2820     bool m_use_global_module_list;
2821     lldb::addr_t m_module_addr;
2822   };
2823 
2824   CommandObjectTargetModulesList(CommandInterpreter &interpreter)
2825       : CommandObjectParsed(
2826             interpreter, "target modules list",
2827             "List current executable and dependent shared library images.",
2828             "target modules list [<cmd-options>]"),
2829         m_options() {}
2830 
2831   ~CommandObjectTargetModulesList() override = default;
2832 
2833   Options *GetOptions() override { return &m_options; }
2834 
2835 protected:
2836   bool DoExecute(Args &command, CommandReturnObject &result) override {
2837     Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
2838     const bool use_global_module_list = m_options.m_use_global_module_list;
2839     // Define a local module list here to ensure it lives longer than any
2840     // "locker"
2841     // object which might lock its contents below (through the "module_list_ptr"
2842     // variable).
2843     ModuleList module_list;
2844     if (target == nullptr && !use_global_module_list) {
2845       result.AppendError("invalid target, create a debug target using the "
2846                          "'target create' command");
2847       result.SetStatus(eReturnStatusFailed);
2848       return false;
2849     } else {
2850       if (target) {
2851         uint32_t addr_byte_size =
2852             target->GetArchitecture().GetAddressByteSize();
2853         result.GetOutputStream().SetAddressByteSize(addr_byte_size);
2854         result.GetErrorStream().SetAddressByteSize(addr_byte_size);
2855       }
2856       // Dump all sections for all modules images
2857       Stream &strm = result.GetOutputStream();
2858 
2859       if (m_options.m_module_addr != LLDB_INVALID_ADDRESS) {
2860         if (target) {
2861           Address module_address;
2862           if (module_address.SetLoadAddress(m_options.m_module_addr, target)) {
2863             ModuleSP module_sp(module_address.GetModule());
2864             if (module_sp) {
2865               PrintModule(target, module_sp.get(), 0, strm);
2866               result.SetStatus(eReturnStatusSuccessFinishResult);
2867             } else {
2868               result.AppendErrorWithFormat(
2869                   "Couldn't find module matching address: 0x%" PRIx64 ".",
2870                   m_options.m_module_addr);
2871               result.SetStatus(eReturnStatusFailed);
2872             }
2873           } else {
2874             result.AppendErrorWithFormat(
2875                 "Couldn't find module containing address: 0x%" PRIx64 ".",
2876                 m_options.m_module_addr);
2877             result.SetStatus(eReturnStatusFailed);
2878           }
2879         } else {
2880           result.AppendError(
2881               "Can only look up modules by address with a valid target.");
2882           result.SetStatus(eReturnStatusFailed);
2883         }
2884         return result.Succeeded();
2885       }
2886 
2887       size_t num_modules = 0;
2888 
2889       // This locker will be locked on the mutex in module_list_ptr if it is
2890       // non-nullptr.
2891       // Otherwise it will lock the AllocationModuleCollectionMutex when
2892       // accessing
2893       // the global module list directly.
2894       std::unique_lock<std::recursive_mutex> guard(
2895           Module::GetAllocationModuleCollectionMutex(), std::defer_lock);
2896 
2897       const ModuleList *module_list_ptr = nullptr;
2898       const size_t argc = command.GetArgumentCount();
2899       if (argc == 0) {
2900         if (use_global_module_list) {
2901           guard.lock();
2902           num_modules = Module::GetNumberAllocatedModules();
2903         } else {
2904           module_list_ptr = &target->GetImages();
2905         }
2906       } else {
2907         for (size_t i = 0; i < argc; ++i) {
2908           // Dump specified images (by basename or fullpath)
2909           const char *arg_cstr = command.GetArgumentAtIndex(i);
2910           const size_t num_matches = FindModulesByName(
2911               target, arg_cstr, module_list, use_global_module_list);
2912           if (num_matches == 0) {
2913             if (argc == 1) {
2914               result.AppendErrorWithFormat("no modules found that match '%s'",
2915                                            arg_cstr);
2916               result.SetStatus(eReturnStatusFailed);
2917               return false;
2918             }
2919           }
2920         }
2921 
2922         module_list_ptr = &module_list;
2923       }
2924 
2925       std::unique_lock<std::recursive_mutex> lock;
2926       if (module_list_ptr != nullptr) {
2927         lock =
2928             std::unique_lock<std::recursive_mutex>(module_list_ptr->GetMutex());
2929 
2930         num_modules = module_list_ptr->GetSize();
2931       }
2932 
2933       if (num_modules > 0) {
2934         for (uint32_t image_idx = 0; image_idx < num_modules; ++image_idx) {
2935           ModuleSP module_sp;
2936           Module *module;
2937           if (module_list_ptr) {
2938             module_sp = module_list_ptr->GetModuleAtIndexUnlocked(image_idx);
2939             module = module_sp.get();
2940           } else {
2941             module = Module::GetAllocatedModuleAtIndex(image_idx);
2942             module_sp = module->shared_from_this();
2943           }
2944 
2945           const size_t indent = strm.Printf("[%3u] ", image_idx);
2946           PrintModule(target, module, indent, strm);
2947         }
2948         result.SetStatus(eReturnStatusSuccessFinishResult);
2949       } else {
2950         if (argc) {
2951           if (use_global_module_list)
2952             result.AppendError(
2953                 "the global module list has no matching modules");
2954           else
2955             result.AppendError("the target has no matching modules");
2956         } else {
2957           if (use_global_module_list)
2958             result.AppendError("the global module list is empty");
2959           else
2960             result.AppendError(
2961                 "the target has no associated executable images");
2962         }
2963         result.SetStatus(eReturnStatusFailed);
2964         return false;
2965       }
2966     }
2967     return result.Succeeded();
2968   }
2969 
2970   void PrintModule(Target *target, Module *module, int indent, Stream &strm) {
2971     if (module == nullptr) {
2972       strm.PutCString("Null module");
2973       return;
2974     }
2975 
2976     bool dump_object_name = false;
2977     if (m_options.m_format_array.empty()) {
2978       m_options.m_format_array.push_back(std::make_pair('u', 0));
2979       m_options.m_format_array.push_back(std::make_pair('h', 0));
2980       m_options.m_format_array.push_back(std::make_pair('f', 0));
2981       m_options.m_format_array.push_back(std::make_pair('S', 0));
2982     }
2983     const size_t num_entries = m_options.m_format_array.size();
2984     bool print_space = false;
2985     for (size_t i = 0; i < num_entries; ++i) {
2986       if (print_space)
2987         strm.PutChar(' ');
2988       print_space = true;
2989       const char format_char = m_options.m_format_array[i].first;
2990       uint32_t width = m_options.m_format_array[i].second;
2991       switch (format_char) {
2992       case 'A':
2993         DumpModuleArchitecture(strm, module, false, width);
2994         break;
2995 
2996       case 't':
2997         DumpModuleArchitecture(strm, module, true, width);
2998         break;
2999 
3000       case 'f':
3001         DumpFullpath(strm, &module->GetFileSpec(), width);
3002         dump_object_name = true;
3003         break;
3004 
3005       case 'd':
3006         DumpDirectory(strm, &module->GetFileSpec(), width);
3007         break;
3008 
3009       case 'b':
3010         DumpBasename(strm, &module->GetFileSpec(), width);
3011         dump_object_name = true;
3012         break;
3013 
3014       case 'h':
3015       case 'o':
3016         // Image header address
3017         {
3018           uint32_t addr_nibble_width =
3019               target ? (target->GetArchitecture().GetAddressByteSize() * 2)
3020                      : 16;
3021 
3022           ObjectFile *objfile = module->GetObjectFile();
3023           if (objfile) {
3024             Address header_addr(objfile->GetHeaderAddress());
3025             if (header_addr.IsValid()) {
3026               if (target && !target->GetSectionLoadList().IsEmpty()) {
3027                 lldb::addr_t header_load_addr =
3028                     header_addr.GetLoadAddress(target);
3029                 if (header_load_addr == LLDB_INVALID_ADDRESS) {
3030                   header_addr.Dump(&strm, target,
3031                                    Address::DumpStyleModuleWithFileAddress,
3032                                    Address::DumpStyleFileAddress);
3033                 } else {
3034                   if (format_char == 'o') {
3035                     // Show the offset of slide for the image
3036                     strm.Printf(
3037                         "0x%*.*" PRIx64, addr_nibble_width, addr_nibble_width,
3038                         header_load_addr - header_addr.GetFileAddress());
3039                   } else {
3040                     // Show the load address of the image
3041                     strm.Printf("0x%*.*" PRIx64, addr_nibble_width,
3042                                 addr_nibble_width, header_load_addr);
3043                   }
3044                 }
3045                 break;
3046               }
3047               // The address was valid, but the image isn't loaded, output the
3048               // address in an appropriate format
3049               header_addr.Dump(&strm, target, Address::DumpStyleFileAddress);
3050               break;
3051             }
3052           }
3053           strm.Printf("%*s", addr_nibble_width + 2, "");
3054         }
3055         break;
3056 
3057       case 'r': {
3058         size_t ref_count = 0;
3059         ModuleSP module_sp(module->shared_from_this());
3060         if (module_sp) {
3061           // Take one away to make sure we don't count our local "module_sp"
3062           ref_count = module_sp.use_count() - 1;
3063         }
3064         if (width)
3065           strm.Printf("{%*" PRIu64 "}", width, (uint64_t)ref_count);
3066         else
3067           strm.Printf("{%" PRIu64 "}", (uint64_t)ref_count);
3068       } break;
3069 
3070       case 's':
3071       case 'S': {
3072         const SymbolVendor *symbol_vendor = module->GetSymbolVendor();
3073         if (symbol_vendor) {
3074           const FileSpec symfile_spec = symbol_vendor->GetMainFileSpec();
3075           if (format_char == 'S') {
3076             // Dump symbol file only if different from module file
3077             if (!symfile_spec || symfile_spec == module->GetFileSpec()) {
3078               print_space = false;
3079               break;
3080             }
3081             // Add a newline and indent past the index
3082             strm.Printf("\n%*s", indent, "");
3083           }
3084           DumpFullpath(strm, &symfile_spec, width);
3085           dump_object_name = true;
3086           break;
3087         }
3088         strm.Printf("%.*s", width, "<NONE>");
3089       } break;
3090 
3091       case 'm':
3092         module->GetModificationTime().Dump(&strm, width);
3093         break;
3094 
3095       case 'p':
3096         strm.Printf("%p", static_cast<void *>(module));
3097         break;
3098 
3099       case 'u':
3100         DumpModuleUUID(strm, module);
3101         break;
3102 
3103       default:
3104         break;
3105       }
3106     }
3107     if (dump_object_name) {
3108       const char *object_name = module->GetObjectName().GetCString();
3109       if (object_name)
3110         strm.Printf("(%s)", object_name);
3111     }
3112     strm.EOL();
3113   }
3114 
3115   CommandOptions m_options;
3116 };
3117 
3118 OptionDefinition
3119     CommandObjectTargetModulesList::CommandOptions::g_option_table[] = {
3120         // clang-format off
3121   {LLDB_OPT_SET_1, false, "address",        'a', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeAddressOrExpression, "Display the image at this address."},
3122   {LLDB_OPT_SET_1, false, "arch",           'A', OptionParser::eOptionalArgument, nullptr, nullptr, 0, eArgTypeWidth,               "Display the architecture when listing images."},
3123   {LLDB_OPT_SET_1, false, "triple",         't', OptionParser::eOptionalArgument, nullptr, nullptr, 0, eArgTypeWidth,               "Display the triple when listing images."},
3124   {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."},
3125   {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)."},
3126   {LLDB_OPT_SET_1, false, "uuid",           'u', OptionParser::eNoArgument,       nullptr, nullptr, 0, eArgTypeNone,                "Display the UUID when listing images."},
3127   {LLDB_OPT_SET_1, false, "fullpath",       'f', OptionParser::eOptionalArgument, nullptr, nullptr, 0, eArgTypeWidth,               "Display the fullpath to the image object file."},
3128   {LLDB_OPT_SET_1, false, "directory",      'd', OptionParser::eOptionalArgument, nullptr, nullptr, 0, eArgTypeWidth,               "Display the directory with optional width for the image object file."},
3129   {LLDB_OPT_SET_1, false, "basename",       'b', OptionParser::eOptionalArgument, nullptr, nullptr, 0, eArgTypeWidth,               "Display the basename with optional width for the image object file."},
3130   {LLDB_OPT_SET_1, false, "symfile",        's', OptionParser::eOptionalArgument, nullptr, nullptr, 0, eArgTypeWidth,               "Display the fullpath to the image symbol file with optional width."},
3131   {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."},
3132   {LLDB_OPT_SET_1, false, "mod-time",       'm', OptionParser::eOptionalArgument, nullptr, nullptr, 0, eArgTypeWidth,               "Display the modification time with optional width of the module."},
3133   {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."},
3134   {LLDB_OPT_SET_1, false, "pointer",        'p', OptionParser::eOptionalArgument, nullptr, nullptr, 0, eArgTypeNone,                "Display the module pointer."},
3135   {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."},
3136   {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr}
3137         // clang-format on
3138 };
3139 
3140 #pragma mark CommandObjectTargetModulesShowUnwind
3141 
3142 //----------------------------------------------------------------------
3143 // Lookup unwind information in images
3144 //----------------------------------------------------------------------
3145 
3146 class CommandObjectTargetModulesShowUnwind : public CommandObjectParsed {
3147 public:
3148   enum {
3149     eLookupTypeInvalid = -1,
3150     eLookupTypeAddress = 0,
3151     eLookupTypeSymbol,
3152     eLookupTypeFunction,
3153     eLookupTypeFunctionOrSymbol,
3154     kNumLookupTypes
3155   };
3156 
3157   class CommandOptions : public Options {
3158   public:
3159     CommandOptions()
3160         : Options(), m_type(eLookupTypeInvalid), m_str(),
3161           m_addr(LLDB_INVALID_ADDRESS) {}
3162 
3163     ~CommandOptions() override = default;
3164 
3165     Error SetOptionValue(uint32_t option_idx, const char *option_arg,
3166                          ExecutionContext *execution_context) override {
3167       Error error;
3168 
3169       const int short_option = m_getopt_table[option_idx].val;
3170 
3171       switch (short_option) {
3172       case 'a': {
3173         m_str = option_arg;
3174         m_type = eLookupTypeAddress;
3175         m_addr = Args::StringToAddress(execution_context, option_arg,
3176                                        LLDB_INVALID_ADDRESS, &error);
3177         if (m_addr == LLDB_INVALID_ADDRESS)
3178           error.SetErrorStringWithFormat("invalid address string '%s'",
3179                                          option_arg);
3180         break;
3181       }
3182 
3183       case 'n':
3184         m_str = option_arg;
3185         m_type = eLookupTypeFunctionOrSymbol;
3186         break;
3187 
3188       default:
3189         error.SetErrorStringWithFormat("unrecognized option %c.", short_option);
3190         break;
3191       }
3192 
3193       return error;
3194     }
3195 
3196     void OptionParsingStarting(ExecutionContext *execution_context) override {
3197       m_type = eLookupTypeInvalid;
3198       m_str.clear();
3199       m_addr = LLDB_INVALID_ADDRESS;
3200     }
3201 
3202     const OptionDefinition *GetDefinitions() override { return g_option_table; }
3203 
3204     // Options table: Required for subclasses of Options.
3205 
3206     static OptionDefinition g_option_table[];
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 OptionDefinition
3427     CommandObjectTargetModulesShowUnwind::CommandOptions::g_option_table[] = {
3428         // clang-format off
3429   {LLDB_OPT_SET_1, false, "name",    'n', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeFunctionName,        "Show unwind instructions for a function or symbol name."},
3430   {LLDB_OPT_SET_2, false, "address", 'a', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeAddressOrExpression, "Show unwind instructions for a function or symbol containing an address"},
3431   {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr}
3432         // clang-format on
3433 };
3434 
3435 //----------------------------------------------------------------------
3436 // Lookup information in images
3437 //----------------------------------------------------------------------
3438 class CommandObjectTargetModulesLookup : public CommandObjectParsed {
3439 public:
3440   enum {
3441     eLookupTypeInvalid = -1,
3442     eLookupTypeAddress = 0,
3443     eLookupTypeSymbol,
3444     eLookupTypeFileLine, // Line is optional
3445     eLookupTypeFunction,
3446     eLookupTypeFunctionOrSymbol,
3447     eLookupTypeType,
3448     kNumLookupTypes
3449   };
3450 
3451   class CommandOptions : public Options {
3452   public:
3453     CommandOptions() : Options() { OptionParsingStarting(nullptr); }
3454 
3455     ~CommandOptions() override = default;
3456 
3457     Error SetOptionValue(uint32_t option_idx, const char *option_arg,
3458                          ExecutionContext *execution_context) override {
3459       Error error;
3460 
3461       const int short_option = m_getopt_table[option_idx].val;
3462 
3463       switch (short_option) {
3464       case 'a': {
3465         m_type = eLookupTypeAddress;
3466         m_addr = Args::StringToAddress(execution_context, option_arg,
3467                                        LLDB_INVALID_ADDRESS, &error);
3468       } break;
3469 
3470       case 'o':
3471         m_offset = StringConvert::ToUInt64(option_arg, LLDB_INVALID_ADDRESS);
3472         if (m_offset == LLDB_INVALID_ADDRESS)
3473           error.SetErrorStringWithFormat("invalid offset string '%s'",
3474                                          option_arg);
3475         break;
3476 
3477       case 's':
3478         m_str = option_arg;
3479         m_type = eLookupTypeSymbol;
3480         break;
3481 
3482       case 'f':
3483         m_file.SetFile(option_arg, false);
3484         m_type = eLookupTypeFileLine;
3485         break;
3486 
3487       case 'i':
3488         m_include_inlines = false;
3489         break;
3490 
3491       case 'l':
3492         m_line_number = StringConvert::ToUInt32(option_arg, UINT32_MAX);
3493         if (m_line_number == UINT32_MAX)
3494           error.SetErrorStringWithFormat("invalid line number string '%s'",
3495                                          option_arg);
3496         else if (m_line_number == 0)
3497           error.SetErrorString("zero is an invalid line number");
3498         m_type = eLookupTypeFileLine;
3499         break;
3500 
3501       case 'F':
3502         m_str = option_arg;
3503         m_type = eLookupTypeFunction;
3504         break;
3505 
3506       case 'n':
3507         m_str = option_arg;
3508         m_type = eLookupTypeFunctionOrSymbol;
3509         break;
3510 
3511       case 't':
3512         m_str = option_arg;
3513         m_type = eLookupTypeType;
3514         break;
3515 
3516       case 'v':
3517         m_verbose = 1;
3518         break;
3519 
3520       case 'A':
3521         m_print_all = true;
3522         break;
3523 
3524       case 'r':
3525         m_use_regex = true;
3526         break;
3527       }
3528 
3529       return error;
3530     }
3531 
3532     void OptionParsingStarting(ExecutionContext *execution_context) override {
3533       m_type = eLookupTypeInvalid;
3534       m_str.clear();
3535       m_file.Clear();
3536       m_addr = LLDB_INVALID_ADDRESS;
3537       m_offset = 0;
3538       m_line_number = 0;
3539       m_use_regex = false;
3540       m_include_inlines = true;
3541       m_verbose = false;
3542       m_print_all = false;
3543     }
3544 
3545     const OptionDefinition *GetDefinitions() override { return g_option_table; }
3546 
3547     // Options table: Required for subclasses of Options.
3548 
3549     static OptionDefinition g_option_table[];
3550     int m_type;        // Should be a eLookupTypeXXX enum after parsing options
3551     std::string m_str; // Holds name lookup
3552     FileSpec m_file;   // Files for file lookups
3553     lldb::addr_t m_addr; // Holds the address to lookup
3554     lldb::addr_t
3555         m_offset; // Subtract this offset from m_addr before doing lookups.
3556     uint32_t m_line_number; // Line number for file+line lookups
3557     bool m_use_regex;       // Name lookups in m_str are regular expressions.
3558     bool m_include_inlines; // Check for inline entries when looking up by
3559                             // file/line.
3560     bool m_verbose;         // Enable verbose lookup info
3561     bool m_print_all; // Print all matches, even in cases where there's a best
3562                       // match.
3563   };
3564 
3565   CommandObjectTargetModulesLookup(CommandInterpreter &interpreter)
3566       : CommandObjectParsed(interpreter, "target modules lookup",
3567                             "Look up information within executable and "
3568                             "dependent shared library images.",
3569                             nullptr, eCommandRequiresTarget),
3570         m_options() {
3571     CommandArgumentEntry arg;
3572     CommandArgumentData file_arg;
3573 
3574     // Define the first (and only) variant of this arg.
3575     file_arg.arg_type = eArgTypeFilename;
3576     file_arg.arg_repetition = eArgRepeatStar;
3577 
3578     // There is only one variant this argument could be; put it into the
3579     // argument entry.
3580     arg.push_back(file_arg);
3581 
3582     // Push the data for the first argument into the m_arguments vector.
3583     m_arguments.push_back(arg);
3584   }
3585 
3586   ~CommandObjectTargetModulesLookup() override = default;
3587 
3588   Options *GetOptions() override { return &m_options; }
3589 
3590   bool LookupHere(CommandInterpreter &interpreter, CommandReturnObject &result,
3591                   bool &syntax_error) {
3592     switch (m_options.m_type) {
3593     case eLookupTypeAddress:
3594     case eLookupTypeFileLine:
3595     case eLookupTypeFunction:
3596     case eLookupTypeFunctionOrSymbol:
3597     case eLookupTypeSymbol:
3598     default:
3599       return false;
3600     case eLookupTypeType:
3601       break;
3602     }
3603 
3604     StackFrameSP frame = m_exe_ctx.GetFrameSP();
3605 
3606     if (!frame)
3607       return false;
3608 
3609     const SymbolContext &sym_ctx(frame->GetSymbolContext(eSymbolContextModule));
3610 
3611     if (!sym_ctx.module_sp)
3612       return false;
3613 
3614     switch (m_options.m_type) {
3615     default:
3616       return false;
3617     case eLookupTypeType:
3618       if (!m_options.m_str.empty()) {
3619         if (LookupTypeHere(m_interpreter, result.GetOutputStream(), sym_ctx,
3620                            m_options.m_str.c_str(), m_options.m_use_regex)) {
3621           result.SetStatus(eReturnStatusSuccessFinishResult);
3622           return true;
3623         }
3624       }
3625       break;
3626     }
3627 
3628     return true;
3629   }
3630 
3631   bool LookupInModule(CommandInterpreter &interpreter, Module *module,
3632                       CommandReturnObject &result, bool &syntax_error) {
3633     switch (m_options.m_type) {
3634     case eLookupTypeAddress:
3635       if (m_options.m_addr != LLDB_INVALID_ADDRESS) {
3636         if (LookupAddressInModule(
3637                 m_interpreter, result.GetOutputStream(), module,
3638                 eSymbolContextEverything |
3639                     (m_options.m_verbose
3640                          ? static_cast<int>(eSymbolContextVariable)
3641                          : 0),
3642                 m_options.m_addr, m_options.m_offset, m_options.m_verbose)) {
3643           result.SetStatus(eReturnStatusSuccessFinishResult);
3644           return true;
3645         }
3646       }
3647       break;
3648 
3649     case eLookupTypeSymbol:
3650       if (!m_options.m_str.empty()) {
3651         if (LookupSymbolInModule(m_interpreter, result.GetOutputStream(),
3652                                  module, m_options.m_str.c_str(),
3653                                  m_options.m_use_regex, m_options.m_verbose)) {
3654           result.SetStatus(eReturnStatusSuccessFinishResult);
3655           return true;
3656         }
3657       }
3658       break;
3659 
3660     case eLookupTypeFileLine:
3661       if (m_options.m_file) {
3662         if (LookupFileAndLineInModule(
3663                 m_interpreter, result.GetOutputStream(), module,
3664                 m_options.m_file, m_options.m_line_number,
3665                 m_options.m_include_inlines, m_options.m_verbose)) {
3666           result.SetStatus(eReturnStatusSuccessFinishResult);
3667           return true;
3668         }
3669       }
3670       break;
3671 
3672     case eLookupTypeFunctionOrSymbol:
3673     case eLookupTypeFunction:
3674       if (!m_options.m_str.empty()) {
3675         if (LookupFunctionInModule(
3676                 m_interpreter, result.GetOutputStream(), module,
3677                 m_options.m_str.c_str(), m_options.m_use_regex,
3678                 m_options.m_include_inlines,
3679                 m_options.m_type ==
3680                     eLookupTypeFunctionOrSymbol, // include symbols
3681                 m_options.m_verbose)) {
3682           result.SetStatus(eReturnStatusSuccessFinishResult);
3683           return true;
3684         }
3685       }
3686       break;
3687 
3688     case eLookupTypeType:
3689       if (!m_options.m_str.empty()) {
3690         if (LookupTypeInModule(m_interpreter, result.GetOutputStream(), module,
3691                                m_options.m_str.c_str(),
3692                                m_options.m_use_regex)) {
3693           result.SetStatus(eReturnStatusSuccessFinishResult);
3694           return true;
3695         }
3696       }
3697       break;
3698 
3699     default:
3700       m_options.GenerateOptionUsage(
3701           result.GetErrorStream(), this,
3702           GetCommandInterpreter().GetDebugger().GetTerminalWidth());
3703       syntax_error = true;
3704       break;
3705     }
3706 
3707     result.SetStatus(eReturnStatusFailed);
3708     return false;
3709   }
3710 
3711 protected:
3712   bool DoExecute(Args &command, CommandReturnObject &result) override {
3713     Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
3714     if (target == nullptr) {
3715       result.AppendError("invalid target, create a debug target using the "
3716                          "'target create' command");
3717       result.SetStatus(eReturnStatusFailed);
3718       return false;
3719     } else {
3720       bool syntax_error = false;
3721       uint32_t i;
3722       uint32_t num_successful_lookups = 0;
3723       uint32_t addr_byte_size = target->GetArchitecture().GetAddressByteSize();
3724       result.GetOutputStream().SetAddressByteSize(addr_byte_size);
3725       result.GetErrorStream().SetAddressByteSize(addr_byte_size);
3726       // Dump all sections for all modules images
3727 
3728       if (command.GetArgumentCount() == 0) {
3729         ModuleSP current_module;
3730 
3731         // Where it is possible to look in the current symbol context
3732         // first, try that.  If this search was successful and --all
3733         // was not passed, don't print anything else.
3734         if (LookupHere(m_interpreter, result, syntax_error)) {
3735           result.GetOutputStream().EOL();
3736           num_successful_lookups++;
3737           if (!m_options.m_print_all) {
3738             result.SetStatus(eReturnStatusSuccessFinishResult);
3739             return result.Succeeded();
3740           }
3741         }
3742 
3743         // Dump all sections for all other modules
3744 
3745         const ModuleList &target_modules = target->GetImages();
3746         std::lock_guard<std::recursive_mutex> guard(target_modules.GetMutex());
3747         const size_t num_modules = target_modules.GetSize();
3748         if (num_modules > 0) {
3749           for (i = 0; i < num_modules && !syntax_error; ++i) {
3750             Module *module_pointer =
3751                 target_modules.GetModulePointerAtIndexUnlocked(i);
3752 
3753             if (module_pointer != current_module.get() &&
3754                 LookupInModule(
3755                     m_interpreter,
3756                     target_modules.GetModulePointerAtIndexUnlocked(i), result,
3757                     syntax_error)) {
3758               result.GetOutputStream().EOL();
3759               num_successful_lookups++;
3760             }
3761           }
3762         } else {
3763           result.AppendError("the target has no associated executable images");
3764           result.SetStatus(eReturnStatusFailed);
3765           return false;
3766         }
3767       } else {
3768         // Dump specified images (by basename or fullpath)
3769         const char *arg_cstr;
3770         for (i = 0; (arg_cstr = command.GetArgumentAtIndex(i)) != nullptr &&
3771                     !syntax_error;
3772              ++i) {
3773           ModuleList module_list;
3774           const size_t num_matches =
3775               FindModulesByName(target, arg_cstr, module_list, false);
3776           if (num_matches > 0) {
3777             for (size_t j = 0; j < num_matches; ++j) {
3778               Module *module = module_list.GetModulePointerAtIndex(j);
3779               if (module) {
3780                 if (LookupInModule(m_interpreter, module, result,
3781                                    syntax_error)) {
3782                   result.GetOutputStream().EOL();
3783                   num_successful_lookups++;
3784                 }
3785               }
3786             }
3787           } else
3788             result.AppendWarningWithFormat(
3789                 "Unable to find an image that matches '%s'.\n", arg_cstr);
3790         }
3791       }
3792 
3793       if (num_successful_lookups > 0)
3794         result.SetStatus(eReturnStatusSuccessFinishResult);
3795       else
3796         result.SetStatus(eReturnStatusFailed);
3797     }
3798     return result.Succeeded();
3799   }
3800 
3801   CommandOptions m_options;
3802 };
3803 
3804 OptionDefinition
3805     CommandObjectTargetModulesLookup::CommandOptions::g_option_table[] =
3806         {
3807             // clang-format off
3808   {LLDB_OPT_SET_1,                                  true,  "address",    'a', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeAddressOrExpression, "Lookup an address in one or more target modules."},
3809   {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."},
3810   /* FIXME: re-enable regex for types when the LookupTypeInModule actually uses the regex option: | LLDB_OPT_SET_6 */
3811   {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."},
3812   {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."},
3813   {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."},
3814   {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)."},
3815   {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)."},
3816   {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."},
3817   {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."},
3818   {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."},
3819   {LLDB_OPT_SET_ALL,                                false, "verbose",    'v', OptionParser::eNoArgument,       nullptr, nullptr, 0, eArgTypeNone,                "Enable verbose lookup information."},
3820   {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."},
3821   {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr}
3822             // clang-format on
3823 };
3824 
3825 #pragma mark CommandObjectMultiwordImageSearchPaths
3826 
3827 //-------------------------------------------------------------------------
3828 // CommandObjectMultiwordImageSearchPaths
3829 //-------------------------------------------------------------------------
3830 
3831 class CommandObjectTargetModulesImageSearchPaths
3832     : public CommandObjectMultiword {
3833 public:
3834   CommandObjectTargetModulesImageSearchPaths(CommandInterpreter &interpreter)
3835       : CommandObjectMultiword(
3836             interpreter, "target modules search-paths",
3837             "Commands for managing module search paths for a target.",
3838             "target modules search-paths <subcommand> [<subcommand-options>]") {
3839     LoadSubCommand(
3840         "add", CommandObjectSP(
3841                    new CommandObjectTargetModulesSearchPathsAdd(interpreter)));
3842     LoadSubCommand(
3843         "clear", CommandObjectSP(new CommandObjectTargetModulesSearchPathsClear(
3844                      interpreter)));
3845     LoadSubCommand(
3846         "insert",
3847         CommandObjectSP(
3848             new CommandObjectTargetModulesSearchPathsInsert(interpreter)));
3849     LoadSubCommand(
3850         "list", CommandObjectSP(new CommandObjectTargetModulesSearchPathsList(
3851                     interpreter)));
3852     LoadSubCommand(
3853         "query", CommandObjectSP(new CommandObjectTargetModulesSearchPathsQuery(
3854                      interpreter)));
3855   }
3856 
3857   ~CommandObjectTargetModulesImageSearchPaths() override = default;
3858 };
3859 
3860 #pragma mark CommandObjectTargetModules
3861 
3862 //-------------------------------------------------------------------------
3863 // CommandObjectTargetModules
3864 //-------------------------------------------------------------------------
3865 
3866 class CommandObjectTargetModules : public CommandObjectMultiword {
3867 public:
3868   //------------------------------------------------------------------
3869   // Constructors and Destructors
3870   //------------------------------------------------------------------
3871   CommandObjectTargetModules(CommandInterpreter &interpreter)
3872       : CommandObjectMultiword(interpreter, "target modules",
3873                                "Commands for accessing information for one or "
3874                                "more target modules.",
3875                                "target modules <sub-command> ...") {
3876     LoadSubCommand(
3877         "add", CommandObjectSP(new CommandObjectTargetModulesAdd(interpreter)));
3878     LoadSubCommand("load", CommandObjectSP(new CommandObjectTargetModulesLoad(
3879                                interpreter)));
3880     LoadSubCommand("dump", CommandObjectSP(new CommandObjectTargetModulesDump(
3881                                interpreter)));
3882     LoadSubCommand("list", CommandObjectSP(new CommandObjectTargetModulesList(
3883                                interpreter)));
3884     LoadSubCommand(
3885         "lookup",
3886         CommandObjectSP(new CommandObjectTargetModulesLookup(interpreter)));
3887     LoadSubCommand(
3888         "search-paths",
3889         CommandObjectSP(
3890             new CommandObjectTargetModulesImageSearchPaths(interpreter)));
3891     LoadSubCommand(
3892         "show-unwind",
3893         CommandObjectSP(new CommandObjectTargetModulesShowUnwind(interpreter)));
3894   }
3895 
3896   ~CommandObjectTargetModules() override = default;
3897 
3898 private:
3899   //------------------------------------------------------------------
3900   // For CommandObjectTargetModules only
3901   //------------------------------------------------------------------
3902   DISALLOW_COPY_AND_ASSIGN(CommandObjectTargetModules);
3903 };
3904 
3905 class CommandObjectTargetSymbolsAdd : public CommandObjectParsed {
3906 public:
3907   CommandObjectTargetSymbolsAdd(CommandInterpreter &interpreter)
3908       : CommandObjectParsed(
3909             interpreter, "target symbols add",
3910             "Add a debug symbol file to one of the target's current modules by "
3911             "specifying a path to a debug symbols file, or using the options "
3912             "to specify a module to download symbols for.",
3913             "target symbols add [<symfile>]", eCommandRequiresTarget),
3914         m_option_group(),
3915         m_file_option(
3916             LLDB_OPT_SET_1, false, "shlib", 's',
3917             CommandCompletions::eModuleCompletion, eArgTypeShlibName,
3918             "Fullpath or basename for module to find debug symbols for."),
3919         m_current_frame_option(
3920             LLDB_OPT_SET_2, false, "frame", 'F',
3921             "Locate the debug symbols the currently selected frame.", false,
3922             true)
3923 
3924   {
3925     m_option_group.Append(&m_uuid_option_group, LLDB_OPT_SET_ALL,
3926                           LLDB_OPT_SET_1);
3927     m_option_group.Append(&m_file_option, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
3928     m_option_group.Append(&m_current_frame_option, LLDB_OPT_SET_2,
3929                           LLDB_OPT_SET_2);
3930     m_option_group.Finalize();
3931   }
3932 
3933   ~CommandObjectTargetSymbolsAdd() override = default;
3934 
3935   int HandleArgumentCompletion(Args &input, int &cursor_index,
3936                                int &cursor_char_position,
3937                                OptionElementVector &opt_element_vector,
3938                                int match_start_point, int max_return_elements,
3939                                bool &word_complete,
3940                                StringList &matches) override {
3941     std::string completion_str(input.GetArgumentAtIndex(cursor_index));
3942     completion_str.erase(cursor_char_position);
3943 
3944     CommandCompletions::InvokeCommonCompletionCallbacks(
3945         GetCommandInterpreter(), CommandCompletions::eDiskFileCompletion,
3946         completion_str.c_str(), match_start_point, max_return_elements, nullptr,
3947         word_complete, matches);
3948     return matches.GetSize();
3949   }
3950 
3951   Options *GetOptions() override { return &m_option_group; }
3952 
3953 protected:
3954   bool AddModuleSymbols(Target *target, ModuleSpec &module_spec, bool &flush,
3955                         CommandReturnObject &result) {
3956     const FileSpec &symbol_fspec = module_spec.GetSymbolFileSpec();
3957     if (symbol_fspec) {
3958       char symfile_path[PATH_MAX];
3959       symbol_fspec.GetPath(symfile_path, sizeof(symfile_path));
3960 
3961       if (!module_spec.GetUUID().IsValid()) {
3962         if (!module_spec.GetFileSpec() && !module_spec.GetPlatformFileSpec())
3963           module_spec.GetFileSpec().GetFilename() = symbol_fspec.GetFilename();
3964       }
3965       // We now have a module that represents a symbol file
3966       // that can be used for a module that might exist in the
3967       // current target, so we need to find that module in the
3968       // target
3969       ModuleList matching_module_list;
3970 
3971       size_t num_matches = 0;
3972       // First extract all module specs from the symbol file
3973       lldb_private::ModuleSpecList symfile_module_specs;
3974       if (ObjectFile::GetModuleSpecifications(module_spec.GetSymbolFileSpec(),
3975                                               0, 0, symfile_module_specs)) {
3976         // Now extract the module spec that matches the target architecture
3977         ModuleSpec target_arch_module_spec;
3978         ModuleSpec symfile_module_spec;
3979         target_arch_module_spec.GetArchitecture() = target->GetArchitecture();
3980         if (symfile_module_specs.FindMatchingModuleSpec(target_arch_module_spec,
3981                                                         symfile_module_spec)) {
3982           // See if it has a UUID?
3983           if (symfile_module_spec.GetUUID().IsValid()) {
3984             // It has a UUID, look for this UUID in the target modules
3985             ModuleSpec symfile_uuid_module_spec;
3986             symfile_uuid_module_spec.GetUUID() = symfile_module_spec.GetUUID();
3987             num_matches = target->GetImages().FindModules(
3988                 symfile_uuid_module_spec, matching_module_list);
3989           }
3990         }
3991 
3992         if (num_matches == 0) {
3993           // No matches yet, iterate through the module specs to find a UUID
3994           // value that
3995           // we can match up to an image in our target
3996           const size_t num_symfile_module_specs =
3997               symfile_module_specs.GetSize();
3998           for (size_t i = 0; i < num_symfile_module_specs && num_matches == 0;
3999                ++i) {
4000             if (symfile_module_specs.GetModuleSpecAtIndex(
4001                     i, symfile_module_spec)) {
4002               if (symfile_module_spec.GetUUID().IsValid()) {
4003                 // It has a UUID, look for this UUID in the target modules
4004                 ModuleSpec symfile_uuid_module_spec;
4005                 symfile_uuid_module_spec.GetUUID() =
4006                     symfile_module_spec.GetUUID();
4007                 num_matches = target->GetImages().FindModules(
4008                     symfile_uuid_module_spec, matching_module_list);
4009               }
4010             }
4011           }
4012         }
4013       }
4014 
4015       // Just try to match up the file by basename if we have no matches at this
4016       // point
4017       if (num_matches == 0)
4018         num_matches =
4019             target->GetImages().FindModules(module_spec, matching_module_list);
4020 
4021       while (num_matches == 0) {
4022         ConstString filename_no_extension(
4023             module_spec.GetFileSpec().GetFileNameStrippingExtension());
4024         // Empty string returned, lets bail
4025         if (!filename_no_extension)
4026           break;
4027 
4028         // Check if there was no extension to strip and the basename is the same
4029         if (filename_no_extension == module_spec.GetFileSpec().GetFilename())
4030           break;
4031 
4032         // Replace basename with one less extension
4033         module_spec.GetFileSpec().GetFilename() = filename_no_extension;
4034 
4035         num_matches =
4036             target->GetImages().FindModules(module_spec, matching_module_list);
4037       }
4038 
4039       if (num_matches > 1) {
4040         result.AppendErrorWithFormat("multiple modules match symbol file '%s', "
4041                                      "use the --uuid option to resolve the "
4042                                      "ambiguity.\n",
4043                                      symfile_path);
4044       } else if (num_matches == 1) {
4045         ModuleSP module_sp(matching_module_list.GetModuleAtIndex(0));
4046 
4047         // The module has not yet created its symbol vendor, we can just
4048         // give the existing target module the symfile path to use for
4049         // when it decides to create it!
4050         module_sp->SetSymbolFileFileSpec(symbol_fspec);
4051 
4052         SymbolVendor *symbol_vendor =
4053             module_sp->GetSymbolVendor(true, &result.GetErrorStream());
4054         if (symbol_vendor) {
4055           SymbolFile *symbol_file = symbol_vendor->GetSymbolFile();
4056 
4057           if (symbol_file) {
4058             ObjectFile *object_file = symbol_file->GetObjectFile();
4059 
4060             if (object_file && object_file->GetFileSpec() == symbol_fspec) {
4061               // Provide feedback that the symfile has been successfully added.
4062               const FileSpec &module_fs = module_sp->GetFileSpec();
4063               result.AppendMessageWithFormat(
4064                   "symbol file '%s' has been added to '%s'\n", symfile_path,
4065                   module_fs.GetPath().c_str());
4066 
4067               // Let clients know something changed in the module
4068               // if it is currently loaded
4069               ModuleList module_list;
4070               module_list.Append(module_sp);
4071               target->SymbolsDidLoad(module_list);
4072 
4073               // Make sure we load any scripting resources that may be embedded
4074               // in the debug info files in case the platform supports that.
4075               Error error;
4076               StreamString feedback_stream;
4077               module_sp->LoadScriptingResourceInTarget(target, error,
4078                                                        &feedback_stream);
4079               if (error.Fail() && error.AsCString())
4080                 result.AppendWarningWithFormat(
4081                     "unable to load scripting data for module %s - error "
4082                     "reported was %s",
4083                     module_sp->GetFileSpec()
4084                         .GetFileNameStrippingExtension()
4085                         .GetCString(),
4086                     error.AsCString());
4087               else if (feedback_stream.GetSize())
4088                 result.AppendWarningWithFormat("%s", feedback_stream.GetData());
4089 
4090               flush = true;
4091               result.SetStatus(eReturnStatusSuccessFinishResult);
4092               return true;
4093             }
4094           }
4095         }
4096         // Clear the symbol file spec if anything went wrong
4097         module_sp->SetSymbolFileFileSpec(FileSpec());
4098       }
4099 
4100       if (module_spec.GetUUID().IsValid()) {
4101         StreamString ss_symfile_uuid;
4102         module_spec.GetUUID().Dump(&ss_symfile_uuid);
4103         result.AppendErrorWithFormat(
4104             "symbol file '%s' (%s) does not match any existing module%s\n",
4105             symfile_path, ss_symfile_uuid.GetData(),
4106             (symbol_fspec.GetFileType() != FileSpec::eFileTypeRegular)
4107                 ? "\n       please specify the full path to the symbol file"
4108                 : "");
4109       } else {
4110         result.AppendErrorWithFormat(
4111             "symbol file '%s' does not match any existing module%s\n",
4112             symfile_path,
4113             (symbol_fspec.GetFileType() != FileSpec::eFileTypeRegular)
4114                 ? "\n       please specify the full path to the symbol file"
4115                 : "");
4116       }
4117     } else {
4118       result.AppendError(
4119           "one or more executable image paths must be specified");
4120     }
4121     result.SetStatus(eReturnStatusFailed);
4122     return false;
4123   }
4124 
4125   bool DoExecute(Args &args, CommandReturnObject &result) override {
4126     Target *target = m_exe_ctx.GetTargetPtr();
4127     result.SetStatus(eReturnStatusFailed);
4128     bool flush = false;
4129     ModuleSpec module_spec;
4130     const bool uuid_option_set =
4131         m_uuid_option_group.GetOptionValue().OptionWasSet();
4132     const bool file_option_set = m_file_option.GetOptionValue().OptionWasSet();
4133     const bool frame_option_set =
4134         m_current_frame_option.GetOptionValue().OptionWasSet();
4135     const size_t argc = args.GetArgumentCount();
4136 
4137     if (argc == 0) {
4138       if (uuid_option_set || file_option_set || frame_option_set) {
4139         bool success = false;
4140         bool error_set = false;
4141         if (frame_option_set) {
4142           Process *process = m_exe_ctx.GetProcessPtr();
4143           if (process) {
4144             const StateType process_state = process->GetState();
4145             if (StateIsStoppedState(process_state, true)) {
4146               StackFrame *frame = m_exe_ctx.GetFramePtr();
4147               if (frame) {
4148                 ModuleSP frame_module_sp(
4149                     frame->GetSymbolContext(eSymbolContextModule).module_sp);
4150                 if (frame_module_sp) {
4151                   if (frame_module_sp->GetPlatformFileSpec().Exists()) {
4152                     module_spec.GetArchitecture() =
4153                         frame_module_sp->GetArchitecture();
4154                     module_spec.GetFileSpec() =
4155                         frame_module_sp->GetPlatformFileSpec();
4156                   }
4157                   module_spec.GetUUID() = frame_module_sp->GetUUID();
4158                   success = module_spec.GetUUID().IsValid() ||
4159                             module_spec.GetFileSpec();
4160                 } else {
4161                   result.AppendError("frame has no module");
4162                   error_set = true;
4163                 }
4164               } else {
4165                 result.AppendError("invalid current frame");
4166                 error_set = true;
4167               }
4168             } else {
4169               result.AppendErrorWithFormat("process is not stopped: %s",
4170                                            StateAsCString(process_state));
4171               error_set = true;
4172             }
4173           } else {
4174             result.AppendError(
4175                 "a process must exist in order to use the --frame option");
4176             error_set = true;
4177           }
4178         } else {
4179           if (uuid_option_set) {
4180             module_spec.GetUUID() =
4181                 m_uuid_option_group.GetOptionValue().GetCurrentValue();
4182             success |= module_spec.GetUUID().IsValid();
4183           } else if (file_option_set) {
4184             module_spec.GetFileSpec() =
4185                 m_file_option.GetOptionValue().GetCurrentValue();
4186             ModuleSP module_sp(
4187                 target->GetImages().FindFirstModule(module_spec));
4188             if (module_sp) {
4189               module_spec.GetFileSpec() = module_sp->GetFileSpec();
4190               module_spec.GetPlatformFileSpec() =
4191                   module_sp->GetPlatformFileSpec();
4192               module_spec.GetUUID() = module_sp->GetUUID();
4193               module_spec.GetArchitecture() = module_sp->GetArchitecture();
4194             } else {
4195               module_spec.GetArchitecture() = target->GetArchitecture();
4196             }
4197             success |= module_spec.GetUUID().IsValid() ||
4198                        module_spec.GetFileSpec().Exists();
4199           }
4200         }
4201 
4202         if (success) {
4203           if (Symbols::DownloadObjectAndSymbolFile(module_spec)) {
4204             if (module_spec.GetSymbolFileSpec())
4205               success = AddModuleSymbols(target, module_spec, flush, result);
4206           }
4207         }
4208 
4209         if (!success && !error_set) {
4210           StreamString error_strm;
4211           if (uuid_option_set) {
4212             error_strm.PutCString("unable to find debug symbols for UUID ");
4213             module_spec.GetUUID().Dump(&error_strm);
4214           } else if (file_option_set) {
4215             error_strm.PutCString(
4216                 "unable to find debug symbols for the executable file ");
4217             error_strm << module_spec.GetFileSpec();
4218           } else if (frame_option_set) {
4219             error_strm.PutCString(
4220                 "unable to find debug symbols for the current frame");
4221           }
4222           result.AppendError(error_strm.GetData());
4223         }
4224       } else {
4225         result.AppendError("one or more symbol file paths must be specified, "
4226                            "or options must be specified");
4227       }
4228     } else {
4229       if (uuid_option_set) {
4230         result.AppendError("specify either one or more paths to symbol files "
4231                            "or use the --uuid option without arguments");
4232       } else if (file_option_set) {
4233         result.AppendError("specify either one or more paths to symbol files "
4234                            "or use the --file option without arguments");
4235       } else if (frame_option_set) {
4236         result.AppendError("specify either one or more paths to symbol files "
4237                            "or use the --frame option without arguments");
4238       } else {
4239         PlatformSP platform_sp(target->GetPlatform());
4240 
4241         for (size_t i = 0; i < argc; ++i) {
4242           const char *symfile_path = args.GetArgumentAtIndex(i);
4243           if (symfile_path) {
4244             module_spec.GetSymbolFileSpec().SetFile(symfile_path, true);
4245             if (platform_sp) {
4246               FileSpec symfile_spec;
4247               if (platform_sp
4248                       ->ResolveSymbolFile(*target, module_spec, symfile_spec)
4249                       .Success())
4250                 module_spec.GetSymbolFileSpec() = symfile_spec;
4251             }
4252 
4253             ArchSpec arch;
4254             bool symfile_exists = module_spec.GetSymbolFileSpec().Exists();
4255 
4256             if (symfile_exists) {
4257               if (!AddModuleSymbols(target, module_spec, flush, result))
4258                 break;
4259             } else {
4260               char resolved_symfile_path[PATH_MAX];
4261               if (module_spec.GetSymbolFileSpec().GetPath(
4262                       resolved_symfile_path, sizeof(resolved_symfile_path))) {
4263                 if (strcmp(resolved_symfile_path, symfile_path) != 0) {
4264                   result.AppendErrorWithFormat(
4265                       "invalid module path '%s' with resolved path '%s'\n",
4266                       symfile_path, resolved_symfile_path);
4267                   break;
4268                 }
4269               }
4270               result.AppendErrorWithFormat("invalid module path '%s'\n",
4271                                            symfile_path);
4272               break;
4273             }
4274           }
4275         }
4276       }
4277     }
4278 
4279     if (flush) {
4280       Process *process = m_exe_ctx.GetProcessPtr();
4281       if (process)
4282         process->Flush();
4283     }
4284     return result.Succeeded();
4285   }
4286 
4287   OptionGroupOptions m_option_group;
4288   OptionGroupUUID m_uuid_option_group;
4289   OptionGroupFile m_file_option;
4290   OptionGroupBoolean m_current_frame_option;
4291 };
4292 
4293 #pragma mark CommandObjectTargetSymbols
4294 
4295 //-------------------------------------------------------------------------
4296 // CommandObjectTargetSymbols
4297 //-------------------------------------------------------------------------
4298 
4299 class CommandObjectTargetSymbols : public CommandObjectMultiword {
4300 public:
4301   //------------------------------------------------------------------
4302   // Constructors and Destructors
4303   //------------------------------------------------------------------
4304   CommandObjectTargetSymbols(CommandInterpreter &interpreter)
4305       : CommandObjectMultiword(
4306             interpreter, "target symbols",
4307             "Commands for adding and managing debug symbol files.",
4308             "target symbols <sub-command> ...") {
4309     LoadSubCommand(
4310         "add", CommandObjectSP(new CommandObjectTargetSymbolsAdd(interpreter)));
4311   }
4312 
4313   ~CommandObjectTargetSymbols() override = default;
4314 
4315 private:
4316   //------------------------------------------------------------------
4317   // For CommandObjectTargetModules only
4318   //------------------------------------------------------------------
4319   DISALLOW_COPY_AND_ASSIGN(CommandObjectTargetSymbols);
4320 };
4321 
4322 #pragma mark CommandObjectTargetStopHookAdd
4323 
4324 //-------------------------------------------------------------------------
4325 // CommandObjectTargetStopHookAdd
4326 //-------------------------------------------------------------------------
4327 
4328 class CommandObjectTargetStopHookAdd : public CommandObjectParsed,
4329                                        public IOHandlerDelegateMultiline {
4330 public:
4331   class CommandOptions : public Options {
4332   public:
4333     CommandOptions()
4334         : Options(), m_line_start(0), m_line_end(UINT_MAX),
4335           m_func_name_type_mask(eFunctionNameTypeAuto),
4336           m_sym_ctx_specified(false), m_thread_specified(false),
4337           m_use_one_liner(false), m_one_liner() {}
4338 
4339     ~CommandOptions() override = default;
4340 
4341     const OptionDefinition *GetDefinitions() override { return g_option_table; }
4342 
4343     Error SetOptionValue(uint32_t option_idx, const char *option_arg,
4344                          ExecutionContext *execution_context) override {
4345       Error error;
4346       const int short_option = m_getopt_table[option_idx].val;
4347       bool success;
4348 
4349       switch (short_option) {
4350       case 'c':
4351         m_class_name = option_arg;
4352         m_sym_ctx_specified = true;
4353         break;
4354 
4355       case 'e':
4356         m_line_end = StringConvert::ToUInt32(option_arg, UINT_MAX, 0, &success);
4357         if (!success) {
4358           error.SetErrorStringWithFormat("invalid end line number: \"%s\"",
4359                                          option_arg);
4360           break;
4361         }
4362         m_sym_ctx_specified = true;
4363         break;
4364 
4365       case 'l':
4366         m_line_start = StringConvert::ToUInt32(option_arg, 0, 0, &success);
4367         if (!success) {
4368           error.SetErrorStringWithFormat("invalid start line number: \"%s\"",
4369                                          option_arg);
4370           break;
4371         }
4372         m_sym_ctx_specified = true;
4373         break;
4374 
4375       case 'i':
4376         m_no_inlines = true;
4377         break;
4378 
4379       case 'n':
4380         m_function_name = option_arg;
4381         m_func_name_type_mask |= eFunctionNameTypeAuto;
4382         m_sym_ctx_specified = true;
4383         break;
4384 
4385       case 'f':
4386         m_file_name = option_arg;
4387         m_sym_ctx_specified = true;
4388         break;
4389 
4390       case 's':
4391         m_module_name = option_arg;
4392         m_sym_ctx_specified = true;
4393         break;
4394 
4395       case 't':
4396         m_thread_id =
4397             StringConvert::ToUInt64(option_arg, LLDB_INVALID_THREAD_ID, 0);
4398         if (m_thread_id == LLDB_INVALID_THREAD_ID)
4399           error.SetErrorStringWithFormat("invalid thread id string '%s'",
4400                                          option_arg);
4401         m_thread_specified = true;
4402         break;
4403 
4404       case 'T':
4405         m_thread_name = option_arg;
4406         m_thread_specified = true;
4407         break;
4408 
4409       case 'q':
4410         m_queue_name = option_arg;
4411         m_thread_specified = true;
4412         break;
4413 
4414       case 'x':
4415         m_thread_index = StringConvert::ToUInt32(option_arg, UINT32_MAX, 0);
4416         if (m_thread_id == UINT32_MAX)
4417           error.SetErrorStringWithFormat("invalid thread index string '%s'",
4418                                          option_arg);
4419         m_thread_specified = true;
4420         break;
4421 
4422       case 'o':
4423         m_use_one_liner = true;
4424         m_one_liner = option_arg;
4425         break;
4426 
4427       default:
4428         error.SetErrorStringWithFormat("unrecognized option %c.", short_option);
4429         break;
4430       }
4431       return error;
4432     }
4433 
4434     void OptionParsingStarting(ExecutionContext *execution_context) override {
4435       m_class_name.clear();
4436       m_function_name.clear();
4437       m_line_start = 0;
4438       m_line_end = UINT_MAX;
4439       m_file_name.clear();
4440       m_module_name.clear();
4441       m_func_name_type_mask = eFunctionNameTypeAuto;
4442       m_thread_id = LLDB_INVALID_THREAD_ID;
4443       m_thread_index = UINT32_MAX;
4444       m_thread_name.clear();
4445       m_queue_name.clear();
4446 
4447       m_no_inlines = false;
4448       m_sym_ctx_specified = false;
4449       m_thread_specified = false;
4450 
4451       m_use_one_liner = false;
4452       m_one_liner.clear();
4453     }
4454 
4455     static OptionDefinition g_option_table[];
4456 
4457     std::string m_class_name;
4458     std::string m_function_name;
4459     uint32_t m_line_start;
4460     uint32_t m_line_end;
4461     std::string m_file_name;
4462     std::string m_module_name;
4463     uint32_t m_func_name_type_mask; // A pick from lldb::FunctionNameType.
4464     lldb::tid_t m_thread_id;
4465     uint32_t m_thread_index;
4466     std::string m_thread_name;
4467     std::string m_queue_name;
4468     bool m_sym_ctx_specified;
4469     bool m_no_inlines;
4470     bool m_thread_specified;
4471     // Instance variables to hold the values for one_liner options.
4472     bool m_use_one_liner;
4473     std::string m_one_liner;
4474   };
4475 
4476   CommandObjectTargetStopHookAdd(CommandInterpreter &interpreter)
4477       : CommandObjectParsed(interpreter, "target stop-hook add",
4478                             "Add a hook to be executed when the target stops.",
4479                             "target stop-hook add"),
4480         IOHandlerDelegateMultiline("DONE",
4481                                    IOHandlerDelegate::Completion::LLDBCommand),
4482         m_options() {}
4483 
4484   ~CommandObjectTargetStopHookAdd() override = default;
4485 
4486   Options *GetOptions() override { return &m_options; }
4487 
4488 protected:
4489   void IOHandlerActivated(IOHandler &io_handler) override {
4490     StreamFileSP output_sp(io_handler.GetOutputStreamFile());
4491     if (output_sp) {
4492       output_sp->PutCString(
4493           "Enter your stop hook command(s).  Type 'DONE' to end.\n");
4494       output_sp->Flush();
4495     }
4496   }
4497 
4498   void IOHandlerInputComplete(IOHandler &io_handler,
4499                               std::string &line) override {
4500     if (m_stop_hook_sp) {
4501       if (line.empty()) {
4502         StreamFileSP error_sp(io_handler.GetErrorStreamFile());
4503         if (error_sp) {
4504           error_sp->Printf("error: stop hook #%" PRIu64
4505                            " aborted, no commands.\n",
4506                            m_stop_hook_sp->GetID());
4507           error_sp->Flush();
4508         }
4509         Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
4510         if (target)
4511           target->RemoveStopHookByID(m_stop_hook_sp->GetID());
4512       } else {
4513         m_stop_hook_sp->GetCommandPointer()->SplitIntoLines(line);
4514         StreamFileSP output_sp(io_handler.GetOutputStreamFile());
4515         if (output_sp) {
4516           output_sp->Printf("Stop hook #%" PRIu64 " added.\n",
4517                             m_stop_hook_sp->GetID());
4518           output_sp->Flush();
4519         }
4520       }
4521       m_stop_hook_sp.reset();
4522     }
4523     io_handler.SetIsDone(true);
4524   }
4525 
4526   bool DoExecute(Args &command, CommandReturnObject &result) override {
4527     m_stop_hook_sp.reset();
4528 
4529     Target *target = GetSelectedOrDummyTarget();
4530     if (target) {
4531       Target::StopHookSP new_hook_sp = target->CreateStopHook();
4532 
4533       //  First step, make the specifier.
4534       std::unique_ptr<SymbolContextSpecifier> specifier_ap;
4535       if (m_options.m_sym_ctx_specified) {
4536         specifier_ap.reset(new SymbolContextSpecifier(
4537             m_interpreter.GetDebugger().GetSelectedTarget()));
4538 
4539         if (!m_options.m_module_name.empty()) {
4540           specifier_ap->AddSpecification(
4541               m_options.m_module_name.c_str(),
4542               SymbolContextSpecifier::eModuleSpecified);
4543         }
4544 
4545         if (!m_options.m_class_name.empty()) {
4546           specifier_ap->AddSpecification(
4547               m_options.m_class_name.c_str(),
4548               SymbolContextSpecifier::eClassOrNamespaceSpecified);
4549         }
4550 
4551         if (!m_options.m_file_name.empty()) {
4552           specifier_ap->AddSpecification(
4553               m_options.m_file_name.c_str(),
4554               SymbolContextSpecifier::eFileSpecified);
4555         }
4556 
4557         if (m_options.m_line_start != 0) {
4558           specifier_ap->AddLineSpecification(
4559               m_options.m_line_start,
4560               SymbolContextSpecifier::eLineStartSpecified);
4561         }
4562 
4563         if (m_options.m_line_end != UINT_MAX) {
4564           specifier_ap->AddLineSpecification(
4565               m_options.m_line_end, SymbolContextSpecifier::eLineEndSpecified);
4566         }
4567 
4568         if (!m_options.m_function_name.empty()) {
4569           specifier_ap->AddSpecification(
4570               m_options.m_function_name.c_str(),
4571               SymbolContextSpecifier::eFunctionSpecified);
4572         }
4573       }
4574 
4575       if (specifier_ap)
4576         new_hook_sp->SetSpecifier(specifier_ap.release());
4577 
4578       // Next see if any of the thread options have been entered:
4579 
4580       if (m_options.m_thread_specified) {
4581         ThreadSpec *thread_spec = new ThreadSpec();
4582 
4583         if (m_options.m_thread_id != LLDB_INVALID_THREAD_ID) {
4584           thread_spec->SetTID(m_options.m_thread_id);
4585         }
4586 
4587         if (m_options.m_thread_index != UINT32_MAX)
4588           thread_spec->SetIndex(m_options.m_thread_index);
4589 
4590         if (!m_options.m_thread_name.empty())
4591           thread_spec->SetName(m_options.m_thread_name.c_str());
4592 
4593         if (!m_options.m_queue_name.empty())
4594           thread_spec->SetQueueName(m_options.m_queue_name.c_str());
4595 
4596         new_hook_sp->SetThreadSpecifier(thread_spec);
4597       }
4598       if (m_options.m_use_one_liner) {
4599         // Use one-liner.
4600         new_hook_sp->GetCommandPointer()->AppendString(
4601             m_options.m_one_liner.c_str());
4602         result.AppendMessageWithFormat("Stop hook #%" PRIu64 " added.\n",
4603                                        new_hook_sp->GetID());
4604       } else {
4605         m_stop_hook_sp = new_hook_sp;
4606         m_interpreter.GetLLDBCommandsFromIOHandler(
4607             "> ",     // Prompt
4608             *this,    // IOHandlerDelegate
4609             true,     // Run IOHandler in async mode
4610             nullptr); // Baton for the "io_handler" that will be passed back
4611                       // into our IOHandlerDelegate functions
4612       }
4613       result.SetStatus(eReturnStatusSuccessFinishNoResult);
4614     } else {
4615       result.AppendError("invalid target\n");
4616       result.SetStatus(eReturnStatusFailed);
4617     }
4618 
4619     return result.Succeeded();
4620   }
4621 
4622 private:
4623   CommandOptions m_options;
4624   Target::StopHookSP m_stop_hook_sp;
4625 };
4626 
4627 OptionDefinition
4628     CommandObjectTargetStopHookAdd::CommandOptions::g_option_table[] = {
4629         // clang-format off
4630   {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."},
4631   {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."},
4632   {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."},
4633   {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."},
4634   {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."},
4635   {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."},
4636   {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."},
4637   {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."},
4638   {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."},
4639   {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."},
4640   {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."},
4641   {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr }
4642         // clang-format on
4643 };
4644 
4645 #pragma mark CommandObjectTargetStopHookDelete
4646 
4647 //-------------------------------------------------------------------------
4648 // CommandObjectTargetStopHookDelete
4649 //-------------------------------------------------------------------------
4650 
4651 class CommandObjectTargetStopHookDelete : public CommandObjectParsed {
4652 public:
4653   CommandObjectTargetStopHookDelete(CommandInterpreter &interpreter)
4654       : CommandObjectParsed(interpreter, "target stop-hook delete",
4655                             "Delete a stop-hook.",
4656                             "target stop-hook delete [<idx>]") {}
4657 
4658   ~CommandObjectTargetStopHookDelete() override = default;
4659 
4660 protected:
4661   bool DoExecute(Args &command, CommandReturnObject &result) override {
4662     Target *target = GetSelectedOrDummyTarget();
4663     if (target) {
4664       // FIXME: see if we can use the breakpoint id style parser?
4665       size_t num_args = command.GetArgumentCount();
4666       if (num_args == 0) {
4667         if (!m_interpreter.Confirm("Delete all stop hooks?", true)) {
4668           result.SetStatus(eReturnStatusFailed);
4669           return false;
4670         } else {
4671           target->RemoveAllStopHooks();
4672         }
4673       } else {
4674         bool success;
4675         for (size_t i = 0; i < num_args; i++) {
4676           lldb::user_id_t user_id = StringConvert::ToUInt32(
4677               command.GetArgumentAtIndex(i), 0, 0, &success);
4678           if (!success) {
4679             result.AppendErrorWithFormat("invalid stop hook id: \"%s\".\n",
4680                                          command.GetArgumentAtIndex(i));
4681             result.SetStatus(eReturnStatusFailed);
4682             return false;
4683           }
4684           success = target->RemoveStopHookByID(user_id);
4685           if (!success) {
4686             result.AppendErrorWithFormat("unknown stop hook id: \"%s\".\n",
4687                                          command.GetArgumentAtIndex(i));
4688             result.SetStatus(eReturnStatusFailed);
4689             return false;
4690           }
4691         }
4692       }
4693       result.SetStatus(eReturnStatusSuccessFinishNoResult);
4694     } else {
4695       result.AppendError("invalid target\n");
4696       result.SetStatus(eReturnStatusFailed);
4697     }
4698 
4699     return result.Succeeded();
4700   }
4701 };
4702 
4703 #pragma mark CommandObjectTargetStopHookEnableDisable
4704 
4705 //-------------------------------------------------------------------------
4706 // CommandObjectTargetStopHookEnableDisable
4707 //-------------------------------------------------------------------------
4708 
4709 class CommandObjectTargetStopHookEnableDisable : public CommandObjectParsed {
4710 public:
4711   CommandObjectTargetStopHookEnableDisable(CommandInterpreter &interpreter,
4712                                            bool enable, const char *name,
4713                                            const char *help, const char *syntax)
4714       : CommandObjectParsed(interpreter, name, help, syntax), m_enable(enable) {
4715   }
4716 
4717   ~CommandObjectTargetStopHookEnableDisable() override = default;
4718 
4719 protected:
4720   bool DoExecute(Args &command, CommandReturnObject &result) override {
4721     Target *target = GetSelectedOrDummyTarget();
4722     if (target) {
4723       // FIXME: see if we can use the breakpoint id style parser?
4724       size_t num_args = command.GetArgumentCount();
4725       bool success;
4726 
4727       if (num_args == 0) {
4728         target->SetAllStopHooksActiveState(m_enable);
4729       } else {
4730         for (size_t i = 0; i < num_args; i++) {
4731           lldb::user_id_t user_id = StringConvert::ToUInt32(
4732               command.GetArgumentAtIndex(i), 0, 0, &success);
4733           if (!success) {
4734             result.AppendErrorWithFormat("invalid stop hook id: \"%s\".\n",
4735                                          command.GetArgumentAtIndex(i));
4736             result.SetStatus(eReturnStatusFailed);
4737             return false;
4738           }
4739           success = target->SetStopHookActiveStateByID(user_id, m_enable);
4740           if (!success) {
4741             result.AppendErrorWithFormat("unknown stop hook id: \"%s\".\n",
4742                                          command.GetArgumentAtIndex(i));
4743             result.SetStatus(eReturnStatusFailed);
4744             return false;
4745           }
4746         }
4747       }
4748       result.SetStatus(eReturnStatusSuccessFinishNoResult);
4749     } else {
4750       result.AppendError("invalid target\n");
4751       result.SetStatus(eReturnStatusFailed);
4752     }
4753     return result.Succeeded();
4754   }
4755 
4756 private:
4757   bool m_enable;
4758 };
4759 
4760 #pragma mark CommandObjectTargetStopHookList
4761 
4762 //-------------------------------------------------------------------------
4763 // CommandObjectTargetStopHookList
4764 //-------------------------------------------------------------------------
4765 
4766 class CommandObjectTargetStopHookList : public CommandObjectParsed {
4767 public:
4768   CommandObjectTargetStopHookList(CommandInterpreter &interpreter)
4769       : CommandObjectParsed(interpreter, "target stop-hook list",
4770                             "List all stop-hooks.",
4771                             "target stop-hook list [<type>]") {}
4772 
4773   ~CommandObjectTargetStopHookList() override = default;
4774 
4775 protected:
4776   bool DoExecute(Args &command, CommandReturnObject &result) override {
4777     Target *target = GetSelectedOrDummyTarget();
4778     if (!target) {
4779       result.AppendError("invalid target\n");
4780       result.SetStatus(eReturnStatusFailed);
4781       return result.Succeeded();
4782     }
4783 
4784     size_t num_hooks = target->GetNumStopHooks();
4785     if (num_hooks == 0) {
4786       result.GetOutputStream().PutCString("No stop hooks.\n");
4787     } else {
4788       for (size_t i = 0; i < num_hooks; i++) {
4789         Target::StopHookSP this_hook = target->GetStopHookAtIndex(i);
4790         if (i > 0)
4791           result.GetOutputStream().PutCString("\n");
4792         this_hook->GetDescription(&(result.GetOutputStream()),
4793                                   eDescriptionLevelFull);
4794       }
4795     }
4796     result.SetStatus(eReturnStatusSuccessFinishResult);
4797     return result.Succeeded();
4798   }
4799 };
4800 
4801 #pragma mark CommandObjectMultiwordTargetStopHooks
4802 
4803 //-------------------------------------------------------------------------
4804 // CommandObjectMultiwordTargetStopHooks
4805 //-------------------------------------------------------------------------
4806 
4807 class CommandObjectMultiwordTargetStopHooks : public CommandObjectMultiword {
4808 public:
4809   CommandObjectMultiwordTargetStopHooks(CommandInterpreter &interpreter)
4810       : CommandObjectMultiword(
4811             interpreter, "target stop-hook",
4812             "Commands for operating on debugger target stop-hooks.",
4813             "target stop-hook <subcommand> [<subcommand-options>]") {
4814     LoadSubCommand("add", CommandObjectSP(
4815                               new CommandObjectTargetStopHookAdd(interpreter)));
4816     LoadSubCommand(
4817         "delete",
4818         CommandObjectSP(new CommandObjectTargetStopHookDelete(interpreter)));
4819     LoadSubCommand("disable",
4820                    CommandObjectSP(new CommandObjectTargetStopHookEnableDisable(
4821                        interpreter, false, "target stop-hook disable [<id>]",
4822                        "Disable a stop-hook.", "target stop-hook disable")));
4823     LoadSubCommand("enable",
4824                    CommandObjectSP(new CommandObjectTargetStopHookEnableDisable(
4825                        interpreter, true, "target stop-hook enable [<id>]",
4826                        "Enable a stop-hook.", "target stop-hook enable")));
4827     LoadSubCommand("list", CommandObjectSP(new CommandObjectTargetStopHookList(
4828                                interpreter)));
4829   }
4830 
4831   ~CommandObjectMultiwordTargetStopHooks() override = default;
4832 };
4833 
4834 #pragma mark CommandObjectMultiwordTarget
4835 
4836 //-------------------------------------------------------------------------
4837 // CommandObjectMultiwordTarget
4838 //-------------------------------------------------------------------------
4839 
4840 CommandObjectMultiwordTarget::CommandObjectMultiwordTarget(
4841     CommandInterpreter &interpreter)
4842     : CommandObjectMultiword(interpreter, "target",
4843                              "Commands for operating on debugger targets.",
4844                              "target <subcommand> [<subcommand-options>]") {
4845   LoadSubCommand("create",
4846                  CommandObjectSP(new CommandObjectTargetCreate(interpreter)));
4847   LoadSubCommand("delete",
4848                  CommandObjectSP(new CommandObjectTargetDelete(interpreter)));
4849   LoadSubCommand("list",
4850                  CommandObjectSP(new CommandObjectTargetList(interpreter)));
4851   LoadSubCommand("select",
4852                  CommandObjectSP(new CommandObjectTargetSelect(interpreter)));
4853   LoadSubCommand(
4854       "stop-hook",
4855       CommandObjectSP(new CommandObjectMultiwordTargetStopHooks(interpreter)));
4856   LoadSubCommand("modules",
4857                  CommandObjectSP(new CommandObjectTargetModules(interpreter)));
4858   LoadSubCommand("symbols",
4859                  CommandObjectSP(new CommandObjectTargetSymbols(interpreter)));
4860   LoadSubCommand("variable",
4861                  CommandObjectSP(new CommandObjectTargetVariable(interpreter)));
4862 }
4863 
4864 CommandObjectMultiwordTarget::~CommandObjectMultiwordTarget() = default;
4865