1 //===-- CommandCompletions.cpp --------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "llvm/ADT/SmallString.h"
10 #include "llvm/ADT/StringSet.h"
11 
12 #include "lldb/Breakpoint/Watchpoint.h"
13 #include "lldb/Core/Module.h"
14 #include "lldb/Core/PluginManager.h"
15 #include "lldb/DataFormatters/DataVisualization.h"
16 #include "lldb/Host/FileSystem.h"
17 #include "lldb/Interpreter/CommandCompletions.h"
18 #include "lldb/Interpreter/CommandInterpreter.h"
19 #include "lldb/Interpreter/CommandObject.h"
20 #include "lldb/Interpreter/CommandObjectMultiword.h"
21 #include "lldb/Interpreter/OptionValueProperties.h"
22 #include "lldb/Symbol/CompileUnit.h"
23 #include "lldb/Symbol/Variable.h"
24 #include "lldb/Target/Language.h"
25 #include "lldb/Target/Process.h"
26 #include "lldb/Target/RegisterContext.h"
27 #include "lldb/Target/Thread.h"
28 #include "lldb/Utility/FileSpec.h"
29 #include "lldb/Utility/FileSpecList.h"
30 #include "lldb/Utility/StreamString.h"
31 #include "lldb/Utility/TildeExpressionResolver.h"
32 
33 #include "llvm/Support/FileSystem.h"
34 #include "llvm/Support/Path.h"
35 
36 using namespace lldb_private;
37 
38 // This is the command completion callback that is used to complete the
39 // argument of the option it is bound to (in the OptionDefinition table
40 // below).
41 typedef void (*CompletionCallback)(CommandInterpreter &interpreter,
42                                    CompletionRequest &request,
43                                    // A search filter to limit the search...
44                                    lldb_private::SearchFilter *searcher);
45 
46 struct CommonCompletionElement {
47   uint32_t type;
48   CompletionCallback callback;
49 };
50 
51 bool CommandCompletions::InvokeCommonCompletionCallbacks(
52     CommandInterpreter &interpreter, uint32_t completion_mask,
53     CompletionRequest &request, SearchFilter *searcher) {
54   bool handled = false;
55 
56   const CommonCompletionElement common_completions[] = {
57       {lldb::eSourceFileCompletion, CommandCompletions::SourceFiles},
58       {lldb::eDiskFileCompletion, CommandCompletions::DiskFiles},
59       {lldb::eDiskDirectoryCompletion, CommandCompletions::DiskDirectories},
60       {lldb::eSymbolCompletion, CommandCompletions::Symbols},
61       {lldb::eModuleCompletion, CommandCompletions::Modules},
62       {lldb::eModuleUUIDCompletion, CommandCompletions::ModuleUUIDs},
63       {lldb::eSettingsNameCompletion, CommandCompletions::SettingsNames},
64       {lldb::ePlatformPluginCompletion,
65        CommandCompletions::PlatformPluginNames},
66       {lldb::eArchitectureCompletion, CommandCompletions::ArchitectureNames},
67       {lldb::eVariablePathCompletion, CommandCompletions::VariablePath},
68       {lldb::eRegisterCompletion, CommandCompletions::Registers},
69       {lldb::eBreakpointCompletion, CommandCompletions::Breakpoints},
70       {lldb::eProcessPluginCompletion, CommandCompletions::ProcessPluginNames},
71       {lldb::eDisassemblyFlavorCompletion,
72        CommandCompletions::DisassemblyFlavors},
73       {lldb::eTypeLanguageCompletion, CommandCompletions::TypeLanguages},
74       {lldb::eFrameIndexCompletion, CommandCompletions::FrameIndexes},
75       {lldb::eStopHookIDCompletion, CommandCompletions::StopHookIDs},
76       {lldb::eThreadIndexCompletion, CommandCompletions::ThreadIndexes},
77       {lldb::eWatchpointIDCompletion, CommandCompletions::WatchPointIDs},
78       {lldb::eBreakpointNameCompletion, CommandCompletions::BreakpointNames},
79       {lldb::eProcessIDCompletion, CommandCompletions::ProcessIDs},
80       {lldb::eProcessNameCompletion, CommandCompletions::ProcessNames},
81       {lldb::eRemoteDiskFileCompletion, CommandCompletions::RemoteDiskFiles},
82       {lldb::eRemoteDiskDirectoryCompletion,
83        CommandCompletions::RemoteDiskDirectories},
84       {lldb::eTypeCategoryNameCompletion,
85        CommandCompletions::TypeCategoryNames},
86       {lldb::CompletionType::eNoCompletion,
87        nullptr} // This one has to be last in the list.
88   };
89 
90   for (int i = 0;; i++) {
91     if (common_completions[i].type == lldb::eNoCompletion)
92       break;
93     else if ((common_completions[i].type & completion_mask) ==
94                  common_completions[i].type &&
95              common_completions[i].callback != nullptr) {
96       handled = true;
97       common_completions[i].callback(interpreter, request, searcher);
98     }
99   }
100   return handled;
101 }
102 
103 namespace {
104 // The Completer class is a convenient base class for building searchers that
105 // go along with the SearchFilter passed to the standard Completer functions.
106 class Completer : public Searcher {
107 public:
108   Completer(CommandInterpreter &interpreter, CompletionRequest &request)
109       : m_interpreter(interpreter), m_request(request) {}
110 
111   ~Completer() override = default;
112 
113   CallbackReturn SearchCallback(SearchFilter &filter, SymbolContext &context,
114                                 Address *addr) override = 0;
115 
116   lldb::SearchDepth GetDepth() override = 0;
117 
118   virtual void DoCompletion(SearchFilter *filter) = 0;
119 
120 protected:
121   CommandInterpreter &m_interpreter;
122   CompletionRequest &m_request;
123 
124 private:
125   Completer(const Completer &) = delete;
126   const Completer &operator=(const Completer &) = delete;
127 };
128 } // namespace
129 
130 // SourceFileCompleter implements the source file completer
131 namespace {
132 class SourceFileCompleter : public Completer {
133 public:
134   SourceFileCompleter(CommandInterpreter &interpreter,
135                       CompletionRequest &request)
136       : Completer(interpreter, request) {
137     FileSpec partial_spec(m_request.GetCursorArgumentPrefix());
138     m_file_name = partial_spec.GetFilename().GetCString();
139     m_dir_name = partial_spec.GetDirectory().GetCString();
140   }
141 
142   lldb::SearchDepth GetDepth() override { return lldb::eSearchDepthCompUnit; }
143 
144   Searcher::CallbackReturn SearchCallback(SearchFilter &filter,
145                                           SymbolContext &context,
146                                           Address *addr) override {
147     if (context.comp_unit != nullptr) {
148       const char *cur_file_name =
149           context.comp_unit->GetPrimaryFile().GetFilename().GetCString();
150       const char *cur_dir_name =
151           context.comp_unit->GetPrimaryFile().GetDirectory().GetCString();
152 
153       bool match = false;
154       if (m_file_name && cur_file_name &&
155           strstr(cur_file_name, m_file_name) == cur_file_name)
156         match = true;
157 
158       if (match && m_dir_name && cur_dir_name &&
159           strstr(cur_dir_name, m_dir_name) != cur_dir_name)
160         match = false;
161 
162       if (match) {
163         m_matching_files.AppendIfUnique(context.comp_unit->GetPrimaryFile());
164       }
165     }
166     return Searcher::eCallbackReturnContinue;
167   }
168 
169   void DoCompletion(SearchFilter *filter) override {
170     filter->Search(*this);
171     // Now convert the filelist to completions:
172     for (size_t i = 0; i < m_matching_files.GetSize(); i++) {
173       m_request.AddCompletion(
174           m_matching_files.GetFileSpecAtIndex(i).GetFilename().GetCString());
175     }
176   }
177 
178 private:
179   FileSpecList m_matching_files;
180   const char *m_file_name;
181   const char *m_dir_name;
182 
183   SourceFileCompleter(const SourceFileCompleter &) = delete;
184   const SourceFileCompleter &operator=(const SourceFileCompleter &) = delete;
185 };
186 } // namespace
187 
188 static bool regex_chars(const char comp) {
189   return llvm::StringRef("[](){}+.*|^$\\?").contains(comp);
190 }
191 
192 namespace {
193 class SymbolCompleter : public Completer {
194 
195 public:
196   SymbolCompleter(CommandInterpreter &interpreter, CompletionRequest &request)
197       : Completer(interpreter, request) {
198     std::string regex_str;
199     if (!m_request.GetCursorArgumentPrefix().empty()) {
200       regex_str.append("^");
201       regex_str.append(std::string(m_request.GetCursorArgumentPrefix()));
202     } else {
203       // Match anything since the completion string is empty
204       regex_str.append(".");
205     }
206     std::string::iterator pos =
207         find_if(regex_str.begin() + 1, regex_str.end(), regex_chars);
208     while (pos < regex_str.end()) {
209       pos = regex_str.insert(pos, '\\');
210       pos = find_if(pos + 2, regex_str.end(), regex_chars);
211     }
212     m_regex = RegularExpression(regex_str);
213   }
214 
215   lldb::SearchDepth GetDepth() override { return lldb::eSearchDepthModule; }
216 
217   Searcher::CallbackReturn SearchCallback(SearchFilter &filter,
218                                           SymbolContext &context,
219                                           Address *addr) override {
220     if (context.module_sp) {
221       SymbolContextList sc_list;
222       ModuleFunctionSearchOptions function_options;
223       function_options.include_symbols = true;
224       function_options.include_inlines = true;
225       context.module_sp->FindFunctions(m_regex, function_options, sc_list);
226 
227       // Now add the functions & symbols to the list - only add if unique:
228       for (const SymbolContext &sc : sc_list) {
229         ConstString func_name = sc.GetFunctionName(Mangled::ePreferDemangled);
230         // Ensure that the function name matches the regex. This is more than
231         // a sanity check. It is possible that the demangled function name
232         // does not start with the prefix, for example when it's in an
233         // anonymous namespace.
234         if (!func_name.IsEmpty() && m_regex.Execute(func_name.GetStringRef()))
235           m_match_set.insert(func_name);
236       }
237     }
238     return Searcher::eCallbackReturnContinue;
239   }
240 
241   void DoCompletion(SearchFilter *filter) override {
242     filter->Search(*this);
243     collection::iterator pos = m_match_set.begin(), end = m_match_set.end();
244     for (pos = m_match_set.begin(); pos != end; pos++)
245       m_request.AddCompletion((*pos).GetCString());
246   }
247 
248 private:
249   RegularExpression m_regex;
250   typedef std::set<ConstString> collection;
251   collection m_match_set;
252 
253   SymbolCompleter(const SymbolCompleter &) = delete;
254   const SymbolCompleter &operator=(const SymbolCompleter &) = delete;
255 };
256 } // namespace
257 
258 namespace {
259 class ModuleCompleter : public Completer {
260 public:
261   ModuleCompleter(CommandInterpreter &interpreter, CompletionRequest &request)
262       : Completer(interpreter, request) {
263     FileSpec partial_spec(m_request.GetCursorArgumentPrefix());
264     m_file_name = partial_spec.GetFilename().GetCString();
265     m_dir_name = partial_spec.GetDirectory().GetCString();
266   }
267 
268   lldb::SearchDepth GetDepth() override { return lldb::eSearchDepthModule; }
269 
270   Searcher::CallbackReturn SearchCallback(SearchFilter &filter,
271                                           SymbolContext &context,
272                                           Address *addr) override {
273     if (context.module_sp) {
274       const char *cur_file_name =
275           context.module_sp->GetFileSpec().GetFilename().GetCString();
276       const char *cur_dir_name =
277           context.module_sp->GetFileSpec().GetDirectory().GetCString();
278 
279       bool match = false;
280       if (m_file_name && cur_file_name &&
281           strstr(cur_file_name, m_file_name) == cur_file_name)
282         match = true;
283 
284       if (match && m_dir_name && cur_dir_name &&
285           strstr(cur_dir_name, m_dir_name) != cur_dir_name)
286         match = false;
287 
288       if (match) {
289         m_request.AddCompletion(cur_file_name);
290       }
291     }
292     return Searcher::eCallbackReturnContinue;
293   }
294 
295   void DoCompletion(SearchFilter *filter) override { filter->Search(*this); }
296 
297 private:
298   const char *m_file_name;
299   const char *m_dir_name;
300 
301   ModuleCompleter(const ModuleCompleter &) = delete;
302   const ModuleCompleter &operator=(const ModuleCompleter &) = delete;
303 };
304 } // namespace
305 
306 void CommandCompletions::SourceFiles(CommandInterpreter &interpreter,
307                                      CompletionRequest &request,
308                                      SearchFilter *searcher) {
309   SourceFileCompleter completer(interpreter, request);
310 
311   if (searcher == nullptr) {
312     lldb::TargetSP target_sp = interpreter.GetDebugger().GetSelectedTarget();
313     SearchFilterForUnconstrainedSearches null_searcher(target_sp);
314     completer.DoCompletion(&null_searcher);
315   } else {
316     completer.DoCompletion(searcher);
317   }
318 }
319 
320 static void DiskFilesOrDirectories(const llvm::Twine &partial_name,
321                                    bool only_directories,
322                                    CompletionRequest &request,
323                                    TildeExpressionResolver &Resolver) {
324   llvm::SmallString<256> CompletionBuffer;
325   llvm::SmallString<256> Storage;
326   partial_name.toVector(CompletionBuffer);
327 
328   if (CompletionBuffer.size() >= PATH_MAX)
329     return;
330 
331   namespace path = llvm::sys::path;
332 
333   llvm::StringRef SearchDir;
334   llvm::StringRef PartialItem;
335 
336   if (CompletionBuffer.startswith("~")) {
337     llvm::StringRef Buffer = CompletionBuffer;
338     size_t FirstSep =
339         Buffer.find_if([](char c) { return path::is_separator(c); });
340 
341     llvm::StringRef Username = Buffer.take_front(FirstSep);
342     llvm::StringRef Remainder;
343     if (FirstSep != llvm::StringRef::npos)
344       Remainder = Buffer.drop_front(FirstSep + 1);
345 
346     llvm::SmallString<256> Resolved;
347     if (!Resolver.ResolveExact(Username, Resolved)) {
348       // We couldn't resolve it as a full username.  If there were no slashes
349       // then this might be a partial username.   We try to resolve it as such
350       // but after that, we're done regardless of any matches.
351       if (FirstSep == llvm::StringRef::npos) {
352         llvm::StringSet<> MatchSet;
353         Resolver.ResolvePartial(Username, MatchSet);
354         for (const auto &S : MatchSet) {
355           Resolved = S.getKey();
356           path::append(Resolved, path::get_separator());
357           request.AddCompletion(Resolved, "", CompletionMode::Partial);
358         }
359       }
360       return;
361     }
362 
363     // If there was no trailing slash, then we're done as soon as we resolve
364     // the expression to the correct directory.  Otherwise we need to continue
365     // looking for matches within that directory.
366     if (FirstSep == llvm::StringRef::npos) {
367       // Make sure it ends with a separator.
368       path::append(CompletionBuffer, path::get_separator());
369       request.AddCompletion(CompletionBuffer, "", CompletionMode::Partial);
370       return;
371     }
372 
373     // We want to keep the form the user typed, so we special case this to
374     // search in the fully resolved directory, but CompletionBuffer keeps the
375     // unmodified form that the user typed.
376     Storage = Resolved;
377     llvm::StringRef RemainderDir = path::parent_path(Remainder);
378     if (!RemainderDir.empty()) {
379       // Append the remaining path to the resolved directory.
380       Storage.append(path::get_separator());
381       Storage.append(RemainderDir);
382     }
383     SearchDir = Storage;
384   } else if (CompletionBuffer == path::root_directory(CompletionBuffer)) {
385     SearchDir = CompletionBuffer;
386   } else {
387     SearchDir = path::parent_path(CompletionBuffer);
388   }
389 
390   size_t FullPrefixLen = CompletionBuffer.size();
391 
392   PartialItem = path::filename(CompletionBuffer);
393 
394   // path::filename() will return "." when the passed path ends with a
395   // directory separator or the separator when passed the disk root directory.
396   // We have to filter those out, but only when the "." doesn't come from the
397   // completion request itself.
398   if ((PartialItem == "." || PartialItem == path::get_separator()) &&
399       path::is_separator(CompletionBuffer.back()))
400     PartialItem = llvm::StringRef();
401 
402   if (SearchDir.empty()) {
403     llvm::sys::fs::current_path(Storage);
404     SearchDir = Storage;
405   }
406   assert(!PartialItem.contains(path::get_separator()));
407 
408   // SearchDir now contains the directory to search in, and Prefix contains the
409   // text we want to match against items in that directory.
410 
411   FileSystem &fs = FileSystem::Instance();
412   std::error_code EC;
413   llvm::vfs::directory_iterator Iter = fs.DirBegin(SearchDir, EC);
414   llvm::vfs::directory_iterator End;
415   for (; Iter != End && !EC; Iter.increment(EC)) {
416     auto &Entry = *Iter;
417     llvm::ErrorOr<llvm::vfs::Status> Status = fs.GetStatus(Entry.path());
418 
419     if (!Status)
420       continue;
421 
422     auto Name = path::filename(Entry.path());
423 
424     // Omit ".", ".."
425     if (Name == "." || Name == ".." || !Name.startswith(PartialItem))
426       continue;
427 
428     bool is_dir = Status->isDirectory();
429 
430     // If it's a symlink, then we treat it as a directory as long as the target
431     // is a directory.
432     if (Status->isSymlink()) {
433       FileSpec symlink_filespec(Entry.path());
434       FileSpec resolved_filespec;
435       auto error = fs.ResolveSymbolicLink(symlink_filespec, resolved_filespec);
436       if (error.Success())
437         is_dir = fs.IsDirectory(symlink_filespec);
438     }
439 
440     if (only_directories && !is_dir)
441       continue;
442 
443     // Shrink it back down so that it just has the original prefix the user
444     // typed and remove the part of the name which is common to the located
445     // item and what the user typed.
446     CompletionBuffer.resize(FullPrefixLen);
447     Name = Name.drop_front(PartialItem.size());
448     CompletionBuffer.append(Name);
449 
450     if (is_dir) {
451       path::append(CompletionBuffer, path::get_separator());
452     }
453 
454     CompletionMode mode =
455         is_dir ? CompletionMode::Partial : CompletionMode::Normal;
456     request.AddCompletion(CompletionBuffer, "", mode);
457   }
458 }
459 
460 static void DiskFilesOrDirectories(const llvm::Twine &partial_name,
461                                    bool only_directories, StringList &matches,
462                                    TildeExpressionResolver &Resolver) {
463   CompletionResult result;
464   std::string partial_name_str = partial_name.str();
465   CompletionRequest request(partial_name_str, partial_name_str.size(), result);
466   DiskFilesOrDirectories(partial_name, only_directories, request, Resolver);
467   result.GetMatches(matches);
468 }
469 
470 static void DiskFilesOrDirectories(CompletionRequest &request,
471                                    bool only_directories) {
472   StandardTildeExpressionResolver resolver;
473   DiskFilesOrDirectories(request.GetCursorArgumentPrefix(), only_directories,
474                          request, resolver);
475 }
476 
477 void CommandCompletions::DiskFiles(CommandInterpreter &interpreter,
478                                    CompletionRequest &request,
479                                    SearchFilter *searcher) {
480   DiskFilesOrDirectories(request, /*only_dirs*/ false);
481 }
482 
483 void CommandCompletions::DiskFiles(const llvm::Twine &partial_file_name,
484                                    StringList &matches,
485                                    TildeExpressionResolver &Resolver) {
486   DiskFilesOrDirectories(partial_file_name, false, matches, Resolver);
487 }
488 
489 void CommandCompletions::DiskDirectories(CommandInterpreter &interpreter,
490                                          CompletionRequest &request,
491                                          SearchFilter *searcher) {
492   DiskFilesOrDirectories(request, /*only_dirs*/ true);
493 }
494 
495 void CommandCompletions::DiskDirectories(const llvm::Twine &partial_file_name,
496                                          StringList &matches,
497                                          TildeExpressionResolver &Resolver) {
498   DiskFilesOrDirectories(partial_file_name, true, matches, Resolver);
499 }
500 
501 void CommandCompletions::RemoteDiskFiles(CommandInterpreter &interpreter,
502                                          CompletionRequest &request,
503                                          SearchFilter *searcher) {
504   lldb::PlatformSP platform_sp =
505       interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform();
506   if (platform_sp)
507     platform_sp->AutoCompleteDiskFileOrDirectory(request, false);
508 }
509 
510 void CommandCompletions::RemoteDiskDirectories(CommandInterpreter &interpreter,
511                                                CompletionRequest &request,
512                                                SearchFilter *searcher) {
513   lldb::PlatformSP platform_sp =
514       interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform();
515   if (platform_sp)
516     platform_sp->AutoCompleteDiskFileOrDirectory(request, true);
517 }
518 
519 void CommandCompletions::Modules(CommandInterpreter &interpreter,
520                                  CompletionRequest &request,
521                                  SearchFilter *searcher) {
522   ModuleCompleter completer(interpreter, request);
523 
524   if (searcher == nullptr) {
525     lldb::TargetSP target_sp = interpreter.GetDebugger().GetSelectedTarget();
526     SearchFilterForUnconstrainedSearches null_searcher(target_sp);
527     completer.DoCompletion(&null_searcher);
528   } else {
529     completer.DoCompletion(searcher);
530   }
531 }
532 
533 void CommandCompletions::ModuleUUIDs(CommandInterpreter &interpreter,
534                                      CompletionRequest &request,
535                                      SearchFilter *searcher) {
536   const ExecutionContext &exe_ctx = interpreter.GetExecutionContext();
537   if (!exe_ctx.HasTargetScope())
538     return;
539 
540   exe_ctx.GetTargetPtr()->GetImages().ForEach(
541       [&request](const lldb::ModuleSP &module) {
542         StreamString strm;
543         module->GetDescription(strm.AsRawOstream(),
544                                lldb::eDescriptionLevelInitial);
545         request.TryCompleteCurrentArg(module->GetUUID().GetAsString(),
546                                       strm.GetString());
547         return true;
548       });
549 }
550 
551 void CommandCompletions::Symbols(CommandInterpreter &interpreter,
552                                  CompletionRequest &request,
553                                  SearchFilter *searcher) {
554   SymbolCompleter completer(interpreter, request);
555 
556   if (searcher == nullptr) {
557     lldb::TargetSP target_sp = interpreter.GetDebugger().GetSelectedTarget();
558     SearchFilterForUnconstrainedSearches null_searcher(target_sp);
559     completer.DoCompletion(&null_searcher);
560   } else {
561     completer.DoCompletion(searcher);
562   }
563 }
564 
565 void CommandCompletions::SettingsNames(CommandInterpreter &interpreter,
566                                        CompletionRequest &request,
567                                        SearchFilter *searcher) {
568   // Cache the full setting name list
569   static StringList g_property_names;
570   if (g_property_names.GetSize() == 0) {
571     // Generate the full setting name list on demand
572     lldb::OptionValuePropertiesSP properties_sp(
573         interpreter.GetDebugger().GetValueProperties());
574     if (properties_sp) {
575       StreamString strm;
576       properties_sp->DumpValue(nullptr, strm, OptionValue::eDumpOptionName);
577       const std::string &str = std::string(strm.GetString());
578       g_property_names.SplitIntoLines(str.c_str(), str.size());
579     }
580   }
581 
582   for (const std::string &s : g_property_names)
583     request.TryCompleteCurrentArg(s);
584 }
585 
586 void CommandCompletions::PlatformPluginNames(CommandInterpreter &interpreter,
587                                              CompletionRequest &request,
588                                              SearchFilter *searcher) {
589   PluginManager::AutoCompletePlatformName(request.GetCursorArgumentPrefix(),
590                                           request);
591 }
592 
593 void CommandCompletions::ArchitectureNames(CommandInterpreter &interpreter,
594                                            CompletionRequest &request,
595                                            SearchFilter *searcher) {
596   ArchSpec::AutoComplete(request);
597 }
598 
599 void CommandCompletions::VariablePath(CommandInterpreter &interpreter,
600                                       CompletionRequest &request,
601                                       SearchFilter *searcher) {
602   Variable::AutoComplete(interpreter.GetExecutionContext(), request);
603 }
604 
605 void CommandCompletions::Registers(CommandInterpreter &interpreter,
606                                    CompletionRequest &request,
607                                    SearchFilter *searcher) {
608   std::string reg_prefix;
609   if (request.GetCursorArgumentPrefix().startswith("$"))
610     reg_prefix = "$";
611 
612   RegisterContext *reg_ctx =
613       interpreter.GetExecutionContext().GetRegisterContext();
614   if (!reg_ctx)
615     return;
616 
617   const size_t reg_num = reg_ctx->GetRegisterCount();
618   for (size_t reg_idx = 0; reg_idx < reg_num; ++reg_idx) {
619     const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoAtIndex(reg_idx);
620     request.TryCompleteCurrentArg(reg_prefix + reg_info->name,
621                                   reg_info->alt_name);
622   }
623 }
624 
625 void CommandCompletions::Breakpoints(CommandInterpreter &interpreter,
626                                      CompletionRequest &request,
627                                      SearchFilter *searcher) {
628   lldb::TargetSP target = interpreter.GetDebugger().GetSelectedTarget();
629   if (!target)
630     return;
631 
632   const BreakpointList &breakpoints = target->GetBreakpointList();
633 
634   std::unique_lock<std::recursive_mutex> lock;
635   target->GetBreakpointList().GetListMutex(lock);
636 
637   size_t num_breakpoints = breakpoints.GetSize();
638   if (num_breakpoints == 0)
639     return;
640 
641   for (size_t i = 0; i < num_breakpoints; ++i) {
642     lldb::BreakpointSP bp = breakpoints.GetBreakpointAtIndex(i);
643 
644     StreamString s;
645     bp->GetDescription(&s, lldb::eDescriptionLevelBrief);
646     llvm::StringRef bp_info = s.GetString();
647 
648     const size_t colon_pos = bp_info.find_first_of(':');
649     if (colon_pos != llvm::StringRef::npos)
650       bp_info = bp_info.drop_front(colon_pos + 2);
651 
652     request.TryCompleteCurrentArg(std::to_string(bp->GetID()), bp_info);
653   }
654 }
655 
656 void CommandCompletions::BreakpointNames(CommandInterpreter &interpreter,
657                                          CompletionRequest &request,
658                                          SearchFilter *searcher) {
659   lldb::TargetSP target = interpreter.GetDebugger().GetSelectedTarget();
660   if (!target)
661     return;
662 
663   std::vector<std::string> name_list;
664   target->GetBreakpointNames(name_list);
665 
666   for (const std::string &name : name_list)
667     request.TryCompleteCurrentArg(name);
668 }
669 
670 void CommandCompletions::ProcessPluginNames(CommandInterpreter &interpreter,
671                                             CompletionRequest &request,
672                                             SearchFilter *searcher) {
673   PluginManager::AutoCompleteProcessName(request.GetCursorArgumentPrefix(),
674                                          request);
675 }
676 void CommandCompletions::DisassemblyFlavors(CommandInterpreter &interpreter,
677                                             CompletionRequest &request,
678                                             SearchFilter *searcher) {
679   // Currently the only valid options for disassemble -F are default, and for
680   // Intel architectures, att and intel.
681   static const char *flavors[] = {"default", "att", "intel"};
682   for (const char *flavor : flavors) {
683     request.TryCompleteCurrentArg(flavor);
684   }
685 }
686 
687 void CommandCompletions::ProcessIDs(CommandInterpreter &interpreter,
688                                     CompletionRequest &request,
689                                     SearchFilter *searcher) {
690   lldb::PlatformSP platform_sp(interpreter.GetPlatform(true));
691   if (!platform_sp)
692     return;
693   ProcessInstanceInfoList process_infos;
694   ProcessInstanceInfoMatch match_info;
695   platform_sp->FindProcesses(match_info, process_infos);
696   for (const ProcessInstanceInfo &info : process_infos)
697     request.TryCompleteCurrentArg(std::to_string(info.GetProcessID()),
698                                   info.GetNameAsStringRef());
699 }
700 
701 void CommandCompletions::ProcessNames(CommandInterpreter &interpreter,
702                                       CompletionRequest &request,
703                                       SearchFilter *searcher) {
704   lldb::PlatformSP platform_sp(interpreter.GetPlatform(true));
705   if (!platform_sp)
706     return;
707   ProcessInstanceInfoList process_infos;
708   ProcessInstanceInfoMatch match_info;
709   platform_sp->FindProcesses(match_info, process_infos);
710   for (const ProcessInstanceInfo &info : process_infos)
711     request.TryCompleteCurrentArg(info.GetNameAsStringRef());
712 }
713 
714 void CommandCompletions::TypeLanguages(CommandInterpreter &interpreter,
715                                        CompletionRequest &request,
716                                        SearchFilter *searcher) {
717   for (int bit :
718        Language::GetLanguagesSupportingTypeSystems().bitvector.set_bits()) {
719     request.TryCompleteCurrentArg(
720         Language::GetNameForLanguageType(static_cast<lldb::LanguageType>(bit)));
721   }
722 }
723 
724 void CommandCompletions::FrameIndexes(CommandInterpreter &interpreter,
725                                       CompletionRequest &request,
726                                       SearchFilter *searcher) {
727   const ExecutionContext &exe_ctx = interpreter.GetExecutionContext();
728   if (!exe_ctx.HasProcessScope())
729     return;
730 
731   lldb::ThreadSP thread_sp = exe_ctx.GetThreadSP();
732   Debugger &dbg = interpreter.GetDebugger();
733   const uint32_t frame_num = thread_sp->GetStackFrameCount();
734   for (uint32_t i = 0; i < frame_num; ++i) {
735     lldb::StackFrameSP frame_sp = thread_sp->GetStackFrameAtIndex(i);
736     StreamString strm;
737     // Dumping frames can be slow, allow interruption.
738     if (INTERRUPT_REQUESTED(dbg, "Interrupted in frame completion"))
739       break;
740     frame_sp->Dump(&strm, false, true);
741     request.TryCompleteCurrentArg(std::to_string(i), strm.GetString());
742   }
743 }
744 
745 void CommandCompletions::StopHookIDs(CommandInterpreter &interpreter,
746                                      CompletionRequest &request,
747                                      SearchFilter *searcher) {
748   const lldb::TargetSP target_sp =
749       interpreter.GetExecutionContext().GetTargetSP();
750   if (!target_sp)
751     return;
752 
753   const size_t num = target_sp->GetNumStopHooks();
754   for (size_t idx = 0; idx < num; ++idx) {
755     StreamString strm;
756     // The value 11 is an offset to make the completion description looks
757     // neater.
758     strm.SetIndentLevel(11);
759     const Target::StopHookSP stophook_sp = target_sp->GetStopHookAtIndex(idx);
760     stophook_sp->GetDescription(strm, lldb::eDescriptionLevelInitial);
761     request.TryCompleteCurrentArg(std::to_string(stophook_sp->GetID()),
762                                   strm.GetString());
763   }
764 }
765 
766 void CommandCompletions::ThreadIndexes(CommandInterpreter &interpreter,
767                                        CompletionRequest &request,
768                                        SearchFilter *searcher) {
769   const ExecutionContext &exe_ctx = interpreter.GetExecutionContext();
770   if (!exe_ctx.HasProcessScope())
771     return;
772 
773   ThreadList &threads = exe_ctx.GetProcessPtr()->GetThreadList();
774   lldb::ThreadSP thread_sp;
775   for (uint32_t idx = 0; (thread_sp = threads.GetThreadAtIndex(idx)); ++idx) {
776     StreamString strm;
777     thread_sp->GetStatus(strm, 0, 1, 1, true);
778     request.TryCompleteCurrentArg(std::to_string(thread_sp->GetIndexID()),
779                                   strm.GetString());
780   }
781 }
782 
783 void CommandCompletions::WatchPointIDs(CommandInterpreter &interpreter,
784                                        CompletionRequest &request,
785                                        SearchFilter *searcher) {
786   const ExecutionContext &exe_ctx = interpreter.GetExecutionContext();
787   if (!exe_ctx.HasTargetScope())
788     return;
789 
790   const WatchpointList &wp_list = exe_ctx.GetTargetPtr()->GetWatchpointList();
791   for (lldb::WatchpointSP wp_sp : wp_list.Watchpoints()) {
792     StreamString strm;
793     wp_sp->Dump(&strm);
794     request.TryCompleteCurrentArg(std::to_string(wp_sp->GetID()),
795                                   strm.GetString());
796   }
797 }
798 
799 void CommandCompletions::TypeCategoryNames(CommandInterpreter &interpreter,
800                                            CompletionRequest &request,
801                                            SearchFilter *searcher) {
802   DataVisualization::Categories::ForEach(
803       [&request](const lldb::TypeCategoryImplSP &category_sp) {
804         request.TryCompleteCurrentArg(category_sp->GetName(),
805                                       category_sp->GetDescription());
806         return true;
807       });
808 }
809 
810 void CommandCompletions::CompleteModifiableCmdPathArgs(
811     CommandInterpreter &interpreter, CompletionRequest &request,
812     OptionElementVector &opt_element_vector) {
813   // The only arguments constitute a command path, however, there might be
814   // options interspersed among the arguments, and we need to skip those.  Do that
815   // by copying the args vector, and just dropping all the option bits:
816   Args args = request.GetParsedLine();
817   std::vector<size_t> to_delete;
818   for (auto &elem : opt_element_vector) {
819     to_delete.push_back(elem.opt_pos);
820     if (elem.opt_arg_pos != 0)
821       to_delete.push_back(elem.opt_arg_pos);
822   }
823   sort(to_delete.begin(), to_delete.end(), std::greater<size_t>());
824   for (size_t idx : to_delete)
825     args.DeleteArgumentAtIndex(idx);
826 
827   // At this point, we should only have args, so now lookup the command up to
828   // the cursor element.
829 
830   // There's nothing here but options.  It doesn't seem very useful here to
831   // dump all the commands, so just return.
832   size_t num_args = args.GetArgumentCount();
833   if (num_args == 0)
834     return;
835 
836   // There's just one argument, so we should complete its name:
837   StringList matches;
838   if (num_args == 1) {
839     interpreter.GetUserCommandObject(args.GetArgumentAtIndex(0), &matches,
840                                      nullptr);
841     request.AddCompletions(matches);
842     return;
843   }
844 
845   // There was more than one path element, lets find the containing command:
846   Status error;
847   CommandObjectMultiword *mwc =
848       interpreter.VerifyUserMultiwordCmdPath(args, true, error);
849 
850   // Something was wrong somewhere along the path, but I don't think there's
851   // a good way to go back and fill in the missing elements:
852   if (error.Fail())
853     return;
854 
855   // This should never happen.  We already handled the case of one argument
856   // above, and we can only get Success & nullptr back if there's a one-word
857   // leaf.
858   assert(mwc != nullptr);
859 
860   mwc->GetSubcommandObject(args.GetArgumentAtIndex(num_args - 1), &matches);
861   if (matches.GetSize() == 0)
862     return;
863 
864   request.AddCompletions(matches);
865 }
866