1 //===-- CommandCompletions.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 // C Includes 11 #include <sys/stat.h> 12 #if defined(__APPLE__) || defined(__linux__) 13 #include <pwd.h> 14 #endif 15 16 // C++ Includes 17 // Other libraries and framework includes 18 #include "llvm/ADT/SmallString.h" 19 #include "llvm/ADT/StringSet.h" 20 21 // Project includes 22 #include "lldb/Core/FileSpecList.h" 23 #include "lldb/Core/Module.h" 24 #include "lldb/Core/PluginManager.h" 25 #include "lldb/Host/FileSystem.h" 26 #include "lldb/Interpreter/Args.h" 27 #include "lldb/Interpreter/CommandCompletions.h" 28 #include "lldb/Interpreter/CommandInterpreter.h" 29 #include "lldb/Interpreter/OptionValueProperties.h" 30 #include "lldb/Symbol/CompileUnit.h" 31 #include "lldb/Symbol/Variable.h" 32 #include "lldb/Target/Target.h" 33 #include "lldb/Utility/CleanUp.h" 34 #include "lldb/Utility/FileSpec.h" 35 #include "lldb/Utility/StreamString.h" 36 #include "lldb/Utility/TildeExpressionResolver.h" 37 38 #include "llvm/ADT/SmallString.h" 39 #include "llvm/Support/FileSystem.h" 40 #include "llvm/Support/Path.h" 41 42 using namespace lldb_private; 43 44 CommandCompletions::CommonCompletionElement 45 CommandCompletions::g_common_completions[] = { 46 {eCustomCompletion, nullptr}, 47 {eSourceFileCompletion, CommandCompletions::SourceFiles}, 48 {eDiskFileCompletion, CommandCompletions::DiskFiles}, 49 {eDiskDirectoryCompletion, CommandCompletions::DiskDirectories}, 50 {eSymbolCompletion, CommandCompletions::Symbols}, 51 {eModuleCompletion, CommandCompletions::Modules}, 52 {eSettingsNameCompletion, CommandCompletions::SettingsNames}, 53 {ePlatformPluginCompletion, CommandCompletions::PlatformPluginNames}, 54 {eArchitectureCompletion, CommandCompletions::ArchitectureNames}, 55 {eVariablePathCompletion, CommandCompletions::VariablePath}, 56 {eNoCompletion, nullptr} // This one has to be last in the list. 57 }; 58 59 bool CommandCompletions::InvokeCommonCompletionCallbacks( 60 CommandInterpreter &interpreter, uint32_t completion_mask, 61 llvm::StringRef completion_str, int match_start_point, 62 int max_return_elements, SearchFilter *searcher, bool &word_complete, 63 StringList &matches) { 64 bool handled = false; 65 66 if (completion_mask & eCustomCompletion) 67 return false; 68 69 for (int i = 0;; i++) { 70 if (g_common_completions[i].type == eNoCompletion) 71 break; 72 else if ((g_common_completions[i].type & completion_mask) == 73 g_common_completions[i].type && 74 g_common_completions[i].callback != nullptr) { 75 handled = true; 76 g_common_completions[i].callback(interpreter, completion_str, 77 match_start_point, max_return_elements, 78 searcher, word_complete, matches); 79 } 80 } 81 return handled; 82 } 83 84 int CommandCompletions::SourceFiles(CommandInterpreter &interpreter, 85 llvm::StringRef partial_file_name, 86 int match_start_point, 87 int max_return_elements, 88 SearchFilter *searcher, bool &word_complete, 89 StringList &matches) { 90 word_complete = true; 91 // Find some way to switch "include support files..." 92 SourceFileCompleter completer(interpreter, false, partial_file_name, 93 match_start_point, max_return_elements, 94 matches); 95 96 if (searcher == nullptr) { 97 lldb::TargetSP target_sp = interpreter.GetDebugger().GetSelectedTarget(); 98 SearchFilterForUnconstrainedSearches null_searcher(target_sp); 99 completer.DoCompletion(&null_searcher); 100 } else { 101 completer.DoCompletion(searcher); 102 } 103 return matches.GetSize(); 104 } 105 106 static int DiskFilesOrDirectories(const llvm::Twine &partial_name, 107 bool only_directories, bool &saw_directory, 108 StringList &matches, 109 TildeExpressionResolver &Resolver) { 110 matches.Clear(); 111 112 llvm::SmallString<256> CompletionBuffer; 113 llvm::SmallString<256> Storage; 114 partial_name.toVector(CompletionBuffer); 115 116 if (CompletionBuffer.size() >= PATH_MAX) 117 return 0; 118 119 namespace fs = llvm::sys::fs; 120 namespace path = llvm::sys::path; 121 122 llvm::StringRef SearchDir; 123 llvm::StringRef PartialItem; 124 125 if (CompletionBuffer.startswith("~")) { 126 llvm::StringRef Buffer(CompletionBuffer); 127 size_t FirstSep = 128 Buffer.find_if([](char c) { return path::is_separator(c); }); 129 130 llvm::StringRef Username = Buffer.take_front(FirstSep); 131 llvm::StringRef Remainder; 132 if (FirstSep != llvm::StringRef::npos) 133 Remainder = Buffer.drop_front(FirstSep + 1); 134 135 llvm::SmallString<PATH_MAX> Resolved; 136 if (!Resolver.ResolveExact(Username, Resolved)) { 137 // We couldn't resolve it as a full username. If there were no slashes 138 // then this might be a partial username. We try to resolve it as such 139 // but after that, we're done regardless of any matches. 140 if (FirstSep == llvm::StringRef::npos) { 141 llvm::StringSet<> MatchSet; 142 saw_directory = Resolver.ResolvePartial(Username, MatchSet); 143 for (const auto &S : MatchSet) { 144 Resolved = S.getKey(); 145 path::append(Resolved, path::get_separator()); 146 matches.AppendString(Resolved); 147 } 148 saw_directory = (matches.GetSize() > 0); 149 } 150 return matches.GetSize(); 151 } 152 153 // If there was no trailing slash, then we're done as soon as we resolve the 154 // expression to the correct directory. Otherwise we need to continue 155 // looking for matches within that directory. 156 if (FirstSep == llvm::StringRef::npos) { 157 // Make sure it ends with a separator. 158 path::append(CompletionBuffer, path::get_separator()); 159 saw_directory = true; 160 matches.AppendString(CompletionBuffer); 161 return 1; 162 } 163 164 // We want to keep the form the user typed, so we special case this to 165 // search in the fully resolved directory, but CompletionBuffer keeps the 166 // unmodified form that the user typed. 167 Storage = Resolved; 168 SearchDir = Resolved; 169 } else { 170 SearchDir = path::parent_path(CompletionBuffer); 171 } 172 173 size_t FullPrefixLen = CompletionBuffer.size(); 174 175 PartialItem = path::filename(CompletionBuffer); 176 if (PartialItem == ".") 177 PartialItem = llvm::StringRef(); 178 179 assert(!SearchDir.empty()); 180 assert(!PartialItem.contains(path::get_separator())); 181 182 // SearchDir now contains the directory to search in, and Prefix contains the 183 // text we want to match against items in that directory. 184 185 std::error_code EC; 186 fs::directory_iterator Iter(SearchDir, EC, false); 187 fs::directory_iterator End; 188 for (; Iter != End && !EC; Iter.increment(EC)) { 189 auto &Entry = *Iter; 190 191 auto Name = path::filename(Entry.path()); 192 193 // Omit ".", ".." 194 if (Name == "." || Name == ".." || !Name.startswith(PartialItem)) 195 continue; 196 197 // We have a match. 198 199 fs::file_status st; 200 if ((EC = Entry.status(st))) 201 continue; 202 203 // If it's a symlink, then we treat it as a directory as long as the target 204 // is a directory. 205 bool is_dir = fs::is_directory(st); 206 if (fs::is_symlink_file(st)) { 207 fs::file_status target_st; 208 if (!fs::status(Entry.path(), target_st)) 209 is_dir = fs::is_directory(target_st); 210 } 211 if (only_directories && !is_dir) 212 continue; 213 214 // Shrink it back down so that it just has the original prefix the user 215 // typed and remove the part of the name which is common to the located 216 // item and what the user typed. 217 CompletionBuffer.resize(FullPrefixLen); 218 Name = Name.drop_front(PartialItem.size()); 219 CompletionBuffer.append(Name); 220 221 if (is_dir) { 222 saw_directory = true; 223 path::append(CompletionBuffer, path::get_separator()); 224 } 225 226 matches.AppendString(CompletionBuffer); 227 } 228 229 return matches.GetSize(); 230 } 231 232 int CommandCompletions::DiskFiles(CommandInterpreter &interpreter, 233 llvm::StringRef partial_file_name, 234 int match_start_point, 235 int max_return_elements, 236 SearchFilter *searcher, bool &word_complete, 237 StringList &matches) { 238 word_complete = false; 239 StandardTildeExpressionResolver Resolver; 240 return DiskFiles(partial_file_name, matches, Resolver); 241 } 242 243 int CommandCompletions::DiskFiles(const llvm::Twine &partial_file_name, 244 StringList &matches, 245 TildeExpressionResolver &Resolver) { 246 bool word_complete; 247 int ret_val = DiskFilesOrDirectories(partial_file_name, false, word_complete, 248 matches, Resolver); 249 return ret_val; 250 } 251 252 int CommandCompletions::DiskDirectories( 253 CommandInterpreter &interpreter, llvm::StringRef partial_file_name, 254 int match_start_point, int max_return_elements, SearchFilter *searcher, 255 bool &word_complete, StringList &matches) { 256 word_complete = false; 257 StandardTildeExpressionResolver Resolver; 258 return DiskDirectories(partial_file_name, matches, Resolver); 259 } 260 261 int CommandCompletions::DiskDirectories(const llvm::Twine &partial_file_name, 262 StringList &matches, 263 TildeExpressionResolver &Resolver) { 264 bool word_complete; 265 int ret_val = DiskFilesOrDirectories(partial_file_name, true, word_complete, 266 matches, Resolver); 267 return ret_val; 268 } 269 270 int CommandCompletions::Modules(CommandInterpreter &interpreter, 271 llvm::StringRef partial_file_name, 272 int match_start_point, int max_return_elements, 273 SearchFilter *searcher, bool &word_complete, 274 StringList &matches) { 275 word_complete = true; 276 ModuleCompleter completer(interpreter, partial_file_name, match_start_point, 277 max_return_elements, matches); 278 279 if (searcher == nullptr) { 280 lldb::TargetSP target_sp = interpreter.GetDebugger().GetSelectedTarget(); 281 SearchFilterForUnconstrainedSearches null_searcher(target_sp); 282 completer.DoCompletion(&null_searcher); 283 } else { 284 completer.DoCompletion(searcher); 285 } 286 return matches.GetSize(); 287 } 288 289 int CommandCompletions::Symbols(CommandInterpreter &interpreter, 290 llvm::StringRef partial_file_name, 291 int match_start_point, int max_return_elements, 292 SearchFilter *searcher, bool &word_complete, 293 StringList &matches) { 294 word_complete = true; 295 SymbolCompleter completer(interpreter, partial_file_name, match_start_point, 296 max_return_elements, matches); 297 298 if (searcher == nullptr) { 299 lldb::TargetSP target_sp = interpreter.GetDebugger().GetSelectedTarget(); 300 SearchFilterForUnconstrainedSearches null_searcher(target_sp); 301 completer.DoCompletion(&null_searcher); 302 } else { 303 completer.DoCompletion(searcher); 304 } 305 return matches.GetSize(); 306 } 307 308 int CommandCompletions::SettingsNames( 309 CommandInterpreter &interpreter, llvm::StringRef partial_setting_name, 310 int match_start_point, int max_return_elements, SearchFilter *searcher, 311 bool &word_complete, StringList &matches) { 312 // Cache the full setting name list 313 static StringList g_property_names; 314 if (g_property_names.GetSize() == 0) { 315 // Generate the full setting name list on demand 316 lldb::OptionValuePropertiesSP properties_sp( 317 interpreter.GetDebugger().GetValueProperties()); 318 if (properties_sp) { 319 StreamString strm; 320 properties_sp->DumpValue(nullptr, strm, OptionValue::eDumpOptionName); 321 const std::string &str = strm.GetString(); 322 g_property_names.SplitIntoLines(str.c_str(), str.size()); 323 } 324 } 325 326 size_t exact_matches_idx = SIZE_MAX; 327 const size_t num_matches = g_property_names.AutoComplete( 328 partial_setting_name, matches, exact_matches_idx); 329 word_complete = exact_matches_idx != SIZE_MAX; 330 return num_matches; 331 } 332 333 int CommandCompletions::PlatformPluginNames( 334 CommandInterpreter &interpreter, llvm::StringRef partial_name, 335 int match_start_point, int max_return_elements, SearchFilter *searcher, 336 bool &word_complete, lldb_private::StringList &matches) { 337 const uint32_t num_matches = 338 PluginManager::AutoCompletePlatformName(partial_name, matches); 339 word_complete = num_matches == 1; 340 return num_matches; 341 } 342 343 int CommandCompletions::ArchitectureNames( 344 CommandInterpreter &interpreter, llvm::StringRef partial_name, 345 int match_start_point, int max_return_elements, SearchFilter *searcher, 346 bool &word_complete, lldb_private::StringList &matches) { 347 const uint32_t num_matches = ArchSpec::AutoComplete(partial_name, matches); 348 word_complete = num_matches == 1; 349 return num_matches; 350 } 351 352 int CommandCompletions::VariablePath( 353 CommandInterpreter &interpreter, llvm::StringRef partial_name, 354 int match_start_point, int max_return_elements, SearchFilter *searcher, 355 bool &word_complete, lldb_private::StringList &matches) { 356 return Variable::AutoComplete(interpreter.GetExecutionContext(), partial_name, 357 matches, word_complete); 358 } 359 360 CommandCompletions::Completer::Completer(CommandInterpreter &interpreter, 361 llvm::StringRef completion_str, 362 int match_start_point, 363 int max_return_elements, 364 StringList &matches) 365 : m_interpreter(interpreter), m_completion_str(completion_str), 366 m_match_start_point(match_start_point), 367 m_max_return_elements(max_return_elements), m_matches(matches) {} 368 369 CommandCompletions::Completer::~Completer() = default; 370 371 //---------------------------------------------------------------------- 372 // SourceFileCompleter 373 //---------------------------------------------------------------------- 374 375 CommandCompletions::SourceFileCompleter::SourceFileCompleter( 376 CommandInterpreter &interpreter, bool include_support_files, 377 llvm::StringRef completion_str, int match_start_point, 378 int max_return_elements, StringList &matches) 379 : CommandCompletions::Completer(interpreter, completion_str, 380 match_start_point, max_return_elements, 381 matches), 382 m_include_support_files(include_support_files), m_matching_files() { 383 FileSpec partial_spec(m_completion_str, false); 384 m_file_name = partial_spec.GetFilename().GetCString(); 385 m_dir_name = partial_spec.GetDirectory().GetCString(); 386 } 387 388 Searcher::Depth CommandCompletions::SourceFileCompleter::GetDepth() { 389 return eDepthCompUnit; 390 } 391 392 Searcher::CallbackReturn 393 CommandCompletions::SourceFileCompleter::SearchCallback(SearchFilter &filter, 394 SymbolContext &context, 395 Address *addr, 396 bool complete) { 397 if (context.comp_unit != nullptr) { 398 if (m_include_support_files) { 399 FileSpecList supporting_files = context.comp_unit->GetSupportFiles(); 400 for (size_t sfiles = 0; sfiles < supporting_files.GetSize(); sfiles++) { 401 const FileSpec &sfile_spec = 402 supporting_files.GetFileSpecAtIndex(sfiles); 403 const char *sfile_file_name = sfile_spec.GetFilename().GetCString(); 404 const char *sfile_dir_name = sfile_spec.GetFilename().GetCString(); 405 bool match = false; 406 if (m_file_name && sfile_file_name && 407 strstr(sfile_file_name, m_file_name) == sfile_file_name) 408 match = true; 409 if (match && m_dir_name && sfile_dir_name && 410 strstr(sfile_dir_name, m_dir_name) != sfile_dir_name) 411 match = false; 412 413 if (match) { 414 m_matching_files.AppendIfUnique(sfile_spec); 415 } 416 } 417 } else { 418 const char *cur_file_name = context.comp_unit->GetFilename().GetCString(); 419 const char *cur_dir_name = context.comp_unit->GetDirectory().GetCString(); 420 421 bool match = false; 422 if (m_file_name && cur_file_name && 423 strstr(cur_file_name, m_file_name) == cur_file_name) 424 match = true; 425 426 if (match && m_dir_name && cur_dir_name && 427 strstr(cur_dir_name, m_dir_name) != cur_dir_name) 428 match = false; 429 430 if (match) { 431 m_matching_files.AppendIfUnique(context.comp_unit); 432 } 433 } 434 } 435 return Searcher::eCallbackReturnContinue; 436 } 437 438 size_t 439 CommandCompletions::SourceFileCompleter::DoCompletion(SearchFilter *filter) { 440 filter->Search(*this); 441 // Now convert the filelist to completions: 442 for (size_t i = 0; i < m_matching_files.GetSize(); i++) { 443 m_matches.AppendString( 444 m_matching_files.GetFileSpecAtIndex(i).GetFilename().GetCString()); 445 } 446 return m_matches.GetSize(); 447 } 448 449 //---------------------------------------------------------------------- 450 // SymbolCompleter 451 //---------------------------------------------------------------------- 452 453 static bool regex_chars(const char comp) { 454 return (comp == '[' || comp == ']' || comp == '(' || comp == ')' || 455 comp == '{' || comp == '}' || comp == '+' || comp == '.' || 456 comp == '*' || comp == '|' || comp == '^' || comp == '$' || 457 comp == '\\' || comp == '?'); 458 } 459 460 CommandCompletions::SymbolCompleter::SymbolCompleter( 461 CommandInterpreter &interpreter, llvm::StringRef completion_str, 462 int match_start_point, int max_return_elements, StringList &matches) 463 : CommandCompletions::Completer(interpreter, completion_str, 464 match_start_point, max_return_elements, 465 matches) { 466 std::string regex_str; 467 if (!completion_str.empty()) { 468 regex_str.append("^"); 469 regex_str.append(completion_str); 470 } else { 471 // Match anything since the completion string is empty 472 regex_str.append("."); 473 } 474 std::string::iterator pos = 475 find_if(regex_str.begin() + 1, regex_str.end(), regex_chars); 476 while (pos < regex_str.end()) { 477 pos = regex_str.insert(pos, '\\'); 478 pos = find_if(pos + 2, regex_str.end(), regex_chars); 479 } 480 m_regex.Compile(regex_str); 481 } 482 483 Searcher::Depth CommandCompletions::SymbolCompleter::GetDepth() { 484 return eDepthModule; 485 } 486 487 Searcher::CallbackReturn CommandCompletions::SymbolCompleter::SearchCallback( 488 SearchFilter &filter, SymbolContext &context, Address *addr, 489 bool complete) { 490 if (context.module_sp) { 491 SymbolContextList sc_list; 492 const bool include_symbols = true; 493 const bool include_inlines = true; 494 const bool append = true; 495 context.module_sp->FindFunctions(m_regex, include_symbols, include_inlines, 496 append, sc_list); 497 498 SymbolContext sc; 499 // Now add the functions & symbols to the list - only add if unique: 500 for (uint32_t i = 0; i < sc_list.GetSize(); i++) { 501 if (sc_list.GetContextAtIndex(i, sc)) { 502 ConstString func_name = sc.GetFunctionName(Mangled::ePreferDemangled); 503 if (!func_name.IsEmpty()) 504 m_match_set.insert(func_name); 505 } 506 } 507 } 508 return Searcher::eCallbackReturnContinue; 509 } 510 511 size_t CommandCompletions::SymbolCompleter::DoCompletion(SearchFilter *filter) { 512 filter->Search(*this); 513 collection::iterator pos = m_match_set.begin(), end = m_match_set.end(); 514 for (pos = m_match_set.begin(); pos != end; pos++) 515 m_matches.AppendString((*pos).GetCString()); 516 517 return m_matches.GetSize(); 518 } 519 520 //---------------------------------------------------------------------- 521 // ModuleCompleter 522 //---------------------------------------------------------------------- 523 CommandCompletions::ModuleCompleter::ModuleCompleter( 524 CommandInterpreter &interpreter, llvm::StringRef completion_str, 525 int match_start_point, int max_return_elements, StringList &matches) 526 : CommandCompletions::Completer(interpreter, completion_str, 527 match_start_point, max_return_elements, 528 matches) { 529 FileSpec partial_spec(m_completion_str, false); 530 m_file_name = partial_spec.GetFilename().GetCString(); 531 m_dir_name = partial_spec.GetDirectory().GetCString(); 532 } 533 534 Searcher::Depth CommandCompletions::ModuleCompleter::GetDepth() { 535 return eDepthModule; 536 } 537 538 Searcher::CallbackReturn CommandCompletions::ModuleCompleter::SearchCallback( 539 SearchFilter &filter, SymbolContext &context, Address *addr, 540 bool complete) { 541 if (context.module_sp) { 542 const char *cur_file_name = 543 context.module_sp->GetFileSpec().GetFilename().GetCString(); 544 const char *cur_dir_name = 545 context.module_sp->GetFileSpec().GetDirectory().GetCString(); 546 547 bool match = false; 548 if (m_file_name && cur_file_name && 549 strstr(cur_file_name, m_file_name) == cur_file_name) 550 match = true; 551 552 if (match && m_dir_name && cur_dir_name && 553 strstr(cur_dir_name, m_dir_name) != cur_dir_name) 554 match = false; 555 556 if (match) { 557 m_matches.AppendString(cur_file_name); 558 } 559 } 560 return Searcher::eCallbackReturnContinue; 561 } 562 563 size_t CommandCompletions::ModuleCompleter::DoCompletion(SearchFilter *filter) { 564 filter->Search(*this); 565 return m_matches.GetSize(); 566 } 567