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