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