1 //===-- CommandObjectSource.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 "CommandObjectSource.h" 10 11 #include "lldb/Core/Debugger.h" 12 #include "lldb/Core/FileLineResolver.h" 13 #include "lldb/Core/Module.h" 14 #include "lldb/Core/ModuleSpec.h" 15 #include "lldb/Core/SourceManager.h" 16 #include "lldb/Host/OptionParser.h" 17 #include "lldb/Interpreter/CommandReturnObject.h" 18 #include "lldb/Interpreter/OptionArgParser.h" 19 #include "lldb/Interpreter/OptionValueFileColonLine.h" 20 #include "lldb/Interpreter/Options.h" 21 #include "lldb/Symbol/CompileUnit.h" 22 #include "lldb/Symbol/Function.h" 23 #include "lldb/Symbol/Symbol.h" 24 #include "lldb/Target/SectionLoadList.h" 25 #include "lldb/Target/StackFrame.h" 26 #include "lldb/Utility/FileSpec.h" 27 28 using namespace lldb; 29 using namespace lldb_private; 30 31 #pragma mark CommandObjectSourceInfo 32 // CommandObjectSourceInfo - debug line entries dumping command 33 #define LLDB_OPTIONS_source_info 34 #include "CommandOptions.inc" 35 36 class CommandObjectSourceInfo : public CommandObjectParsed { 37 class CommandOptions : public Options { 38 public: 39 CommandOptions() : Options() {} 40 41 ~CommandOptions() override = default; 42 43 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, 44 ExecutionContext *execution_context) override { 45 Status error; 46 const int short_option = GetDefinitions()[option_idx].short_option; 47 switch (short_option) { 48 case 'l': 49 if (option_arg.getAsInteger(0, start_line)) 50 error.SetErrorStringWithFormat("invalid line number: '%s'", 51 option_arg.str().c_str()); 52 break; 53 54 case 'e': 55 if (option_arg.getAsInteger(0, end_line)) 56 error.SetErrorStringWithFormat("invalid line number: '%s'", 57 option_arg.str().c_str()); 58 break; 59 60 case 'c': 61 if (option_arg.getAsInteger(0, num_lines)) 62 error.SetErrorStringWithFormat("invalid line count: '%s'", 63 option_arg.str().c_str()); 64 break; 65 66 case 'f': 67 file_name = std::string(option_arg); 68 break; 69 70 case 'n': 71 symbol_name = std::string(option_arg); 72 break; 73 74 case 'a': { 75 address = OptionArgParser::ToAddress(execution_context, option_arg, 76 LLDB_INVALID_ADDRESS, &error); 77 } break; 78 case 's': 79 modules.push_back(std::string(option_arg)); 80 break; 81 default: 82 llvm_unreachable("Unimplemented option"); 83 } 84 85 return error; 86 } 87 88 void OptionParsingStarting(ExecutionContext *execution_context) override { 89 file_spec.Clear(); 90 file_name.clear(); 91 symbol_name.clear(); 92 address = LLDB_INVALID_ADDRESS; 93 start_line = 0; 94 end_line = 0; 95 num_lines = 0; 96 modules.clear(); 97 } 98 99 llvm::ArrayRef<OptionDefinition> GetDefinitions() override { 100 return llvm::makeArrayRef(g_source_info_options); 101 } 102 103 // Instance variables to hold the values for command options. 104 FileSpec file_spec; 105 std::string file_name; 106 std::string symbol_name; 107 lldb::addr_t address; 108 uint32_t start_line; 109 uint32_t end_line; 110 uint32_t num_lines; 111 std::vector<std::string> modules; 112 }; 113 114 public: 115 CommandObjectSourceInfo(CommandInterpreter &interpreter) 116 : CommandObjectParsed( 117 interpreter, "source info", 118 "Display source line information for the current target " 119 "process. Defaults to instruction pointer in current stack " 120 "frame.", 121 nullptr, eCommandRequiresTarget), 122 m_options() {} 123 124 ~CommandObjectSourceInfo() override = default; 125 126 Options *GetOptions() override { return &m_options; } 127 128 protected: 129 // Dump the line entries in each symbol context. Return the number of entries 130 // found. If module_list is set, only dump lines contained in one of the 131 // modules. If file_spec is set, only dump lines in the file. If the 132 // start_line option was specified, don't print lines less than start_line. 133 // If the end_line option was specified, don't print lines greater than 134 // end_line. If the num_lines option was specified, dont print more than 135 // num_lines entries. 136 uint32_t DumpLinesInSymbolContexts(Stream &strm, 137 const SymbolContextList &sc_list, 138 const ModuleList &module_list, 139 const FileSpec &file_spec) { 140 uint32_t start_line = m_options.start_line; 141 uint32_t end_line = m_options.end_line; 142 uint32_t num_lines = m_options.num_lines; 143 Target *target = m_exe_ctx.GetTargetPtr(); 144 145 uint32_t num_matches = 0; 146 // Dump all the line entries for the file in the list. 147 ConstString last_module_file_name; 148 uint32_t num_scs = sc_list.GetSize(); 149 for (uint32_t i = 0; i < num_scs; ++i) { 150 SymbolContext sc; 151 sc_list.GetContextAtIndex(i, sc); 152 if (sc.comp_unit) { 153 Module *module = sc.module_sp.get(); 154 CompileUnit *cu = sc.comp_unit; 155 const LineEntry &line_entry = sc.line_entry; 156 assert(module && cu); 157 158 // Are we looking for specific modules, files or lines? 159 if (module_list.GetSize() && 160 module_list.GetIndexForModule(module) == LLDB_INVALID_INDEX32) 161 continue; 162 if (!FileSpec::Match(file_spec, line_entry.file)) 163 continue; 164 if (start_line > 0 && line_entry.line < start_line) 165 continue; 166 if (end_line > 0 && line_entry.line > end_line) 167 continue; 168 if (num_lines > 0 && num_matches > num_lines) 169 continue; 170 171 // Print a new header if the module changed. 172 ConstString module_file_name = module->GetFileSpec().GetFilename(); 173 assert(module_file_name); 174 if (module_file_name != last_module_file_name) { 175 if (num_matches > 0) 176 strm << "\n\n"; 177 strm << "Lines found in module `" << module_file_name << "\n"; 178 } 179 // Dump the line entry. 180 line_entry.GetDescription(&strm, lldb::eDescriptionLevelBrief, cu, 181 target, /*show_address_only=*/false); 182 strm << "\n"; 183 last_module_file_name = module_file_name; 184 num_matches++; 185 } 186 } 187 return num_matches; 188 } 189 190 // Dump the requested line entries for the file in the compilation unit. 191 // Return the number of entries found. If module_list is set, only dump lines 192 // contained in one of the modules. If the start_line option was specified, 193 // don't print lines less than start_line. If the end_line option was 194 // specified, don't print lines greater than end_line. If the num_lines 195 // option was specified, dont print more than num_lines entries. 196 uint32_t DumpFileLinesInCompUnit(Stream &strm, Module *module, 197 CompileUnit *cu, const FileSpec &file_spec) { 198 uint32_t start_line = m_options.start_line; 199 uint32_t end_line = m_options.end_line; 200 uint32_t num_lines = m_options.num_lines; 201 Target *target = m_exe_ctx.GetTargetPtr(); 202 203 uint32_t num_matches = 0; 204 assert(module); 205 if (cu) { 206 assert(file_spec.GetFilename().AsCString()); 207 bool has_path = (file_spec.GetDirectory().AsCString() != nullptr); 208 const FileSpecList &cu_file_list = cu->GetSupportFiles(); 209 size_t file_idx = cu_file_list.FindFileIndex(0, file_spec, has_path); 210 if (file_idx != UINT32_MAX) { 211 // Update the file to how it appears in the CU. 212 const FileSpec &cu_file_spec = 213 cu_file_list.GetFileSpecAtIndex(file_idx); 214 215 // Dump all matching lines at or above start_line for the file in the 216 // CU. 217 ConstString file_spec_name = file_spec.GetFilename(); 218 ConstString module_file_name = module->GetFileSpec().GetFilename(); 219 bool cu_header_printed = false; 220 uint32_t line = start_line; 221 while (true) { 222 LineEntry line_entry; 223 224 // Find the lowest index of a line entry with a line equal to or 225 // higher than 'line'. 226 uint32_t start_idx = 0; 227 start_idx = cu->FindLineEntry(start_idx, line, &cu_file_spec, 228 /*exact=*/false, &line_entry); 229 if (start_idx == UINT32_MAX) 230 // No more line entries for our file in this CU. 231 break; 232 233 if (end_line > 0 && line_entry.line > end_line) 234 break; 235 236 // Loop through to find any other entries for this line, dumping 237 // each. 238 line = line_entry.line; 239 do { 240 num_matches++; 241 if (num_lines > 0 && num_matches > num_lines) 242 break; 243 assert(cu_file_spec == line_entry.file); 244 if (!cu_header_printed) { 245 if (num_matches > 0) 246 strm << "\n\n"; 247 strm << "Lines found for file " << file_spec_name 248 << " in compilation unit " 249 << cu->GetPrimaryFile().GetFilename() << " in `" 250 << module_file_name << "\n"; 251 cu_header_printed = true; 252 } 253 line_entry.GetDescription(&strm, lldb::eDescriptionLevelBrief, cu, 254 target, /*show_address_only=*/false); 255 strm << "\n"; 256 257 // Anymore after this one? 258 start_idx++; 259 start_idx = cu->FindLineEntry(start_idx, line, &cu_file_spec, 260 /*exact=*/true, &line_entry); 261 } while (start_idx != UINT32_MAX); 262 263 // Try the next higher line, starting over at start_idx 0. 264 line++; 265 } 266 } 267 } 268 return num_matches; 269 } 270 271 // Dump the requested line entries for the file in the module. Return the 272 // number of entries found. If module_list is set, only dump lines contained 273 // in one of the modules. If the start_line option was specified, don't print 274 // lines less than start_line. If the end_line option was specified, don't 275 // print lines greater than end_line. If the num_lines option was specified, 276 // dont print more than num_lines entries. 277 uint32_t DumpFileLinesInModule(Stream &strm, Module *module, 278 const FileSpec &file_spec) { 279 uint32_t num_matches = 0; 280 if (module) { 281 // Look through all the compilation units (CUs) in this module for ones 282 // that contain lines of code from this source file. 283 for (size_t i = 0; i < module->GetNumCompileUnits(); i++) { 284 // Look for a matching source file in this CU. 285 CompUnitSP cu_sp(module->GetCompileUnitAtIndex(i)); 286 if (cu_sp) { 287 num_matches += 288 DumpFileLinesInCompUnit(strm, module, cu_sp.get(), file_spec); 289 } 290 } 291 } 292 return num_matches; 293 } 294 295 // Given an address and a list of modules, append the symbol contexts of all 296 // line entries containing the address found in the modules and return the 297 // count of matches. If none is found, return an error in 'error_strm'. 298 size_t GetSymbolContextsForAddress(const ModuleList &module_list, 299 lldb::addr_t addr, 300 SymbolContextList &sc_list, 301 StreamString &error_strm) { 302 Address so_addr; 303 size_t num_matches = 0; 304 assert(module_list.GetSize() > 0); 305 Target *target = m_exe_ctx.GetTargetPtr(); 306 if (target->GetSectionLoadList().IsEmpty()) { 307 // The target isn't loaded yet, we need to lookup the file address in all 308 // modules. Note: the module list option does not apply to addresses. 309 const size_t num_modules = module_list.GetSize(); 310 for (size_t i = 0; i < num_modules; ++i) { 311 ModuleSP module_sp(module_list.GetModuleAtIndex(i)); 312 if (!module_sp) 313 continue; 314 if (module_sp->ResolveFileAddress(addr, so_addr)) { 315 SymbolContext sc; 316 sc.Clear(true); 317 if (module_sp->ResolveSymbolContextForAddress( 318 so_addr, eSymbolContextEverything, sc) & 319 eSymbolContextLineEntry) { 320 sc_list.AppendIfUnique(sc, /*merge_symbol_into_function=*/false); 321 ++num_matches; 322 } 323 } 324 } 325 if (num_matches == 0) 326 error_strm.Printf("Source information for file address 0x%" PRIx64 327 " not found in any modules.\n", 328 addr); 329 } else { 330 // The target has some things loaded, resolve this address to a compile 331 // unit + file + line and display 332 if (target->GetSectionLoadList().ResolveLoadAddress(addr, so_addr)) { 333 ModuleSP module_sp(so_addr.GetModule()); 334 // Check to make sure this module is in our list. 335 if (module_sp && module_list.GetIndexForModule(module_sp.get()) != 336 LLDB_INVALID_INDEX32) { 337 SymbolContext sc; 338 sc.Clear(true); 339 if (module_sp->ResolveSymbolContextForAddress( 340 so_addr, eSymbolContextEverything, sc) & 341 eSymbolContextLineEntry) { 342 sc_list.AppendIfUnique(sc, /*merge_symbol_into_function=*/false); 343 ++num_matches; 344 } else { 345 StreamString addr_strm; 346 so_addr.Dump(&addr_strm, nullptr, 347 Address::DumpStyleModuleWithFileAddress); 348 error_strm.Printf( 349 "Address 0x%" PRIx64 " resolves to %s, but there is" 350 " no source information available for this address.\n", 351 addr, addr_strm.GetData()); 352 } 353 } else { 354 StreamString addr_strm; 355 so_addr.Dump(&addr_strm, nullptr, 356 Address::DumpStyleModuleWithFileAddress); 357 error_strm.Printf("Address 0x%" PRIx64 358 " resolves to %s, but it cannot" 359 " be found in any modules.\n", 360 addr, addr_strm.GetData()); 361 } 362 } else 363 error_strm.Printf("Unable to resolve address 0x%" PRIx64 ".\n", addr); 364 } 365 return num_matches; 366 } 367 368 // Dump the line entries found in functions matching the name specified in 369 // the option. 370 bool DumpLinesInFunctions(CommandReturnObject &result) { 371 SymbolContextList sc_list_funcs; 372 ConstString name(m_options.symbol_name.c_str()); 373 SymbolContextList sc_list_lines; 374 Target *target = m_exe_ctx.GetTargetPtr(); 375 uint32_t addr_byte_size = target->GetArchitecture().GetAddressByteSize(); 376 377 ModuleFunctionSearchOptions function_options; 378 function_options.include_symbols = false; 379 function_options.include_inlines = true; 380 381 // Note: module_list can't be const& because FindFunctionSymbols isn't 382 // const. 383 ModuleList module_list = 384 (m_module_list.GetSize() > 0) ? m_module_list : target->GetImages(); 385 module_list.FindFunctions(name, eFunctionNameTypeAuto, function_options, 386 sc_list_funcs); 387 size_t num_matches = sc_list_funcs.GetSize(); 388 389 if (!num_matches) { 390 // If we didn't find any functions with that name, try searching for 391 // symbols that line up exactly with function addresses. 392 SymbolContextList sc_list_symbols; 393 module_list.FindFunctionSymbols(name, eFunctionNameTypeAuto, 394 sc_list_symbols); 395 size_t num_symbol_matches = sc_list_symbols.GetSize(); 396 for (size_t i = 0; i < num_symbol_matches; i++) { 397 SymbolContext sc; 398 sc_list_symbols.GetContextAtIndex(i, sc); 399 if (sc.symbol && sc.symbol->ValueIsAddress()) { 400 const Address &base_address = sc.symbol->GetAddressRef(); 401 Function *function = base_address.CalculateSymbolContextFunction(); 402 if (function) { 403 sc_list_funcs.Append(SymbolContext(function)); 404 num_matches++; 405 } 406 } 407 } 408 } 409 if (num_matches == 0) { 410 result.AppendErrorWithFormat("Could not find function named \'%s\'.\n", 411 m_options.symbol_name.c_str()); 412 return false; 413 } 414 for (size_t i = 0; i < num_matches; i++) { 415 SymbolContext sc; 416 sc_list_funcs.GetContextAtIndex(i, sc); 417 bool context_found_for_symbol = false; 418 // Loop through all the ranges in the function. 419 AddressRange range; 420 for (uint32_t r = 0; 421 sc.GetAddressRange(eSymbolContextEverything, r, 422 /*use_inline_block_range=*/true, range); 423 ++r) { 424 // Append the symbol contexts for each address in the range to 425 // sc_list_lines. 426 const Address &base_address = range.GetBaseAddress(); 427 const addr_t size = range.GetByteSize(); 428 lldb::addr_t start_addr = base_address.GetLoadAddress(target); 429 if (start_addr == LLDB_INVALID_ADDRESS) 430 start_addr = base_address.GetFileAddress(); 431 lldb::addr_t end_addr = start_addr + size; 432 for (lldb::addr_t addr = start_addr; addr < end_addr; 433 addr += addr_byte_size) { 434 StreamString error_strm; 435 if (!GetSymbolContextsForAddress(module_list, addr, sc_list_lines, 436 error_strm)) 437 result.AppendWarningWithFormat("in symbol '%s': %s", 438 sc.GetFunctionName().AsCString(), 439 error_strm.GetData()); 440 else 441 context_found_for_symbol = true; 442 } 443 } 444 if (!context_found_for_symbol) 445 result.AppendWarningWithFormat("Unable to find line information" 446 " for matching symbol '%s'.\n", 447 sc.GetFunctionName().AsCString()); 448 } 449 if (sc_list_lines.GetSize() == 0) { 450 result.AppendErrorWithFormat("No line information could be found" 451 " for any symbols matching '%s'.\n", 452 name.AsCString()); 453 return false; 454 } 455 FileSpec file_spec; 456 if (!DumpLinesInSymbolContexts(result.GetOutputStream(), sc_list_lines, 457 module_list, file_spec)) { 458 result.AppendErrorWithFormat( 459 "Unable to dump line information for symbol '%s'.\n", 460 name.AsCString()); 461 return false; 462 } 463 return true; 464 } 465 466 // Dump the line entries found for the address specified in the option. 467 bool DumpLinesForAddress(CommandReturnObject &result) { 468 Target *target = m_exe_ctx.GetTargetPtr(); 469 SymbolContextList sc_list; 470 471 StreamString error_strm; 472 if (!GetSymbolContextsForAddress(target->GetImages(), m_options.address, 473 sc_list, error_strm)) { 474 result.AppendErrorWithFormat("%s.\n", error_strm.GetData()); 475 return false; 476 } 477 ModuleList module_list; 478 FileSpec file_spec; 479 if (!DumpLinesInSymbolContexts(result.GetOutputStream(), sc_list, 480 module_list, file_spec)) { 481 result.AppendErrorWithFormat("No modules contain load address 0x%" PRIx64 482 ".\n", 483 m_options.address); 484 return false; 485 } 486 return true; 487 } 488 489 // Dump the line entries found in the file specified in the option. 490 bool DumpLinesForFile(CommandReturnObject &result) { 491 FileSpec file_spec(m_options.file_name); 492 const char *filename = m_options.file_name.c_str(); 493 Target *target = m_exe_ctx.GetTargetPtr(); 494 const ModuleList &module_list = 495 (m_module_list.GetSize() > 0) ? m_module_list : target->GetImages(); 496 497 bool displayed_something = false; 498 const size_t num_modules = module_list.GetSize(); 499 for (uint32_t i = 0; i < num_modules; ++i) { 500 // Dump lines for this module. 501 Module *module = module_list.GetModulePointerAtIndex(i); 502 assert(module); 503 if (DumpFileLinesInModule(result.GetOutputStream(), module, file_spec)) 504 displayed_something = true; 505 } 506 if (!displayed_something) { 507 result.AppendErrorWithFormat("No source filenames matched '%s'.\n", 508 filename); 509 return false; 510 } 511 return true; 512 } 513 514 // Dump the line entries for the current frame. 515 bool DumpLinesForFrame(CommandReturnObject &result) { 516 StackFrame *cur_frame = m_exe_ctx.GetFramePtr(); 517 if (cur_frame == nullptr) { 518 result.AppendError( 519 "No selected frame to use to find the default source."); 520 return false; 521 } else if (!cur_frame->HasDebugInformation()) { 522 result.AppendError("No debug info for the selected frame."); 523 return false; 524 } else { 525 const SymbolContext &sc = 526 cur_frame->GetSymbolContext(eSymbolContextLineEntry); 527 SymbolContextList sc_list; 528 sc_list.Append(sc); 529 ModuleList module_list; 530 FileSpec file_spec; 531 if (!DumpLinesInSymbolContexts(result.GetOutputStream(), sc_list, 532 module_list, file_spec)) { 533 result.AppendError( 534 "No source line info available for the selected frame."); 535 return false; 536 } 537 } 538 return true; 539 } 540 541 bool DoExecute(Args &command, CommandReturnObject &result) override { 542 const size_t argc = command.GetArgumentCount(); 543 544 if (argc != 0) { 545 result.AppendErrorWithFormat("'%s' takes no arguments, only flags.\n", 546 GetCommandName().str().c_str()); 547 return false; 548 } 549 550 Target *target = m_exe_ctx.GetTargetPtr(); 551 if (target == nullptr) { 552 target = GetDebugger().GetSelectedTarget().get(); 553 if (target == nullptr) { 554 result.AppendError("invalid target, create a debug target using the " 555 "'target create' command."); 556 return false; 557 } 558 } 559 560 uint32_t addr_byte_size = target->GetArchitecture().GetAddressByteSize(); 561 result.GetOutputStream().SetAddressByteSize(addr_byte_size); 562 result.GetErrorStream().SetAddressByteSize(addr_byte_size); 563 564 // Collect the list of modules to search. 565 m_module_list.Clear(); 566 if (!m_options.modules.empty()) { 567 for (size_t i = 0, e = m_options.modules.size(); i < e; ++i) { 568 FileSpec module_file_spec(m_options.modules[i]); 569 if (module_file_spec) { 570 ModuleSpec module_spec(module_file_spec); 571 target->GetImages().FindModules(module_spec, m_module_list); 572 if (m_module_list.IsEmpty()) 573 result.AppendWarningWithFormat("No module found for '%s'.\n", 574 m_options.modules[i].c_str()); 575 } 576 } 577 if (!m_module_list.GetSize()) { 578 result.AppendError("No modules match the input."); 579 return false; 580 } 581 } else if (target->GetImages().GetSize() == 0) { 582 result.AppendError("The target has no associated executable images."); 583 return false; 584 } 585 586 // Check the arguments to see what lines we should dump. 587 if (!m_options.symbol_name.empty()) { 588 // Print lines for symbol. 589 if (DumpLinesInFunctions(result)) 590 result.SetStatus(eReturnStatusSuccessFinishResult); 591 else 592 result.SetStatus(eReturnStatusFailed); 593 } else if (m_options.address != LLDB_INVALID_ADDRESS) { 594 // Print lines for an address. 595 if (DumpLinesForAddress(result)) 596 result.SetStatus(eReturnStatusSuccessFinishResult); 597 else 598 result.SetStatus(eReturnStatusFailed); 599 } else if (!m_options.file_name.empty()) { 600 // Dump lines for a file. 601 if (DumpLinesForFile(result)) 602 result.SetStatus(eReturnStatusSuccessFinishResult); 603 else 604 result.SetStatus(eReturnStatusFailed); 605 } else { 606 // Dump the line for the current frame. 607 if (DumpLinesForFrame(result)) 608 result.SetStatus(eReturnStatusSuccessFinishResult); 609 else 610 result.SetStatus(eReturnStatusFailed); 611 } 612 return result.Succeeded(); 613 } 614 615 CommandOptions m_options; 616 ModuleList m_module_list; 617 }; 618 619 #pragma mark CommandObjectSourceList 620 // CommandObjectSourceList 621 #define LLDB_OPTIONS_source_list 622 #include "CommandOptions.inc" 623 624 class CommandObjectSourceList : public CommandObjectParsed { 625 class CommandOptions : public Options { 626 public: 627 CommandOptions() : Options() {} 628 629 ~CommandOptions() override = default; 630 631 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, 632 ExecutionContext *execution_context) override { 633 Status error; 634 const int short_option = GetDefinitions()[option_idx].short_option; 635 switch (short_option) { 636 case 'l': 637 if (option_arg.getAsInteger(0, start_line)) 638 error.SetErrorStringWithFormat("invalid line number: '%s'", 639 option_arg.str().c_str()); 640 break; 641 642 case 'c': 643 if (option_arg.getAsInteger(0, num_lines)) 644 error.SetErrorStringWithFormat("invalid line count: '%s'", 645 option_arg.str().c_str()); 646 break; 647 648 case 'f': 649 file_name = std::string(option_arg); 650 break; 651 652 case 'n': 653 symbol_name = std::string(option_arg); 654 break; 655 656 case 'a': { 657 address = OptionArgParser::ToAddress(execution_context, option_arg, 658 LLDB_INVALID_ADDRESS, &error); 659 } break; 660 case 's': 661 modules.push_back(std::string(option_arg)); 662 break; 663 664 case 'b': 665 show_bp_locs = true; 666 break; 667 case 'r': 668 reverse = true; 669 break; 670 case 'y': 671 { 672 OptionValueFileColonLine value; 673 Status fcl_err = value.SetValueFromString(option_arg); 674 if (!fcl_err.Success()) { 675 error.SetErrorStringWithFormat( 676 "Invalid value for file:line specifier: %s", 677 fcl_err.AsCString()); 678 } else { 679 file_name = value.GetFileSpec().GetPath(); 680 start_line = value.GetLineNumber(); 681 // I don't see anything useful to do with a column number, but I don't 682 // want to complain since someone may well have cut and pasted a 683 // listing from somewhere that included a column. 684 } 685 } break; 686 default: 687 llvm_unreachable("Unimplemented option"); 688 } 689 690 return error; 691 } 692 693 void OptionParsingStarting(ExecutionContext *execution_context) override { 694 file_spec.Clear(); 695 file_name.clear(); 696 symbol_name.clear(); 697 address = LLDB_INVALID_ADDRESS; 698 start_line = 0; 699 num_lines = 0; 700 show_bp_locs = false; 701 reverse = false; 702 modules.clear(); 703 } 704 705 llvm::ArrayRef<OptionDefinition> GetDefinitions() override { 706 return llvm::makeArrayRef(g_source_list_options); 707 } 708 709 // Instance variables to hold the values for command options. 710 FileSpec file_spec; 711 std::string file_name; 712 std::string symbol_name; 713 lldb::addr_t address; 714 uint32_t start_line; 715 uint32_t num_lines; 716 std::vector<std::string> modules; 717 bool show_bp_locs; 718 bool reverse; 719 }; 720 721 public: 722 CommandObjectSourceList(CommandInterpreter &interpreter) 723 : CommandObjectParsed(interpreter, "source list", 724 "Display source code for the current target " 725 "process as specified by options.", 726 nullptr, eCommandRequiresTarget), 727 m_options() {} 728 729 ~CommandObjectSourceList() override = default; 730 731 Options *GetOptions() override { return &m_options; } 732 733 const char *GetRepeatCommand(Args ¤t_command_args, 734 uint32_t index) override { 735 // This is kind of gross, but the command hasn't been parsed yet so we 736 // can't look at the option values for this invocation... I have to scan 737 // the arguments directly. 738 auto iter = 739 llvm::find_if(current_command_args, [](const Args::ArgEntry &e) { 740 return e.ref() == "-r" || e.ref() == "--reverse"; 741 }); 742 if (iter == current_command_args.end()) 743 return m_cmd_name.c_str(); 744 745 if (m_reverse_name.empty()) { 746 m_reverse_name = m_cmd_name; 747 m_reverse_name.append(" -r"); 748 } 749 return m_reverse_name.c_str(); 750 } 751 752 protected: 753 struct SourceInfo { 754 ConstString function; 755 LineEntry line_entry; 756 757 SourceInfo(ConstString name, const LineEntry &line_entry) 758 : function(name), line_entry(line_entry) {} 759 760 SourceInfo() : function(), line_entry() {} 761 762 bool IsValid() const { return (bool)function && line_entry.IsValid(); } 763 764 bool operator==(const SourceInfo &rhs) const { 765 return function == rhs.function && 766 line_entry.original_file == rhs.line_entry.original_file && 767 line_entry.line == rhs.line_entry.line; 768 } 769 770 bool operator!=(const SourceInfo &rhs) const { 771 return function != rhs.function || 772 line_entry.original_file != rhs.line_entry.original_file || 773 line_entry.line != rhs.line_entry.line; 774 } 775 776 bool operator<(const SourceInfo &rhs) const { 777 if (function.GetCString() < rhs.function.GetCString()) 778 return true; 779 if (line_entry.file.GetDirectory().GetCString() < 780 rhs.line_entry.file.GetDirectory().GetCString()) 781 return true; 782 if (line_entry.file.GetFilename().GetCString() < 783 rhs.line_entry.file.GetFilename().GetCString()) 784 return true; 785 if (line_entry.line < rhs.line_entry.line) 786 return true; 787 return false; 788 } 789 }; 790 791 size_t DisplayFunctionSource(const SymbolContext &sc, SourceInfo &source_info, 792 CommandReturnObject &result) { 793 if (!source_info.IsValid()) { 794 source_info.function = sc.GetFunctionName(); 795 source_info.line_entry = sc.GetFunctionStartLineEntry(); 796 } 797 798 if (sc.function) { 799 Target *target = m_exe_ctx.GetTargetPtr(); 800 801 FileSpec start_file; 802 uint32_t start_line; 803 uint32_t end_line; 804 FileSpec end_file; 805 806 if (sc.block == nullptr) { 807 // Not an inlined function 808 sc.function->GetStartLineSourceInfo(start_file, start_line); 809 if (start_line == 0) { 810 result.AppendErrorWithFormat("Could not find line information for " 811 "start of function: \"%s\".\n", 812 source_info.function.GetCString()); 813 return 0; 814 } 815 sc.function->GetEndLineSourceInfo(end_file, end_line); 816 } else { 817 // We have an inlined function 818 start_file = source_info.line_entry.file; 819 start_line = source_info.line_entry.line; 820 end_line = start_line + m_options.num_lines; 821 } 822 823 // This is a little hacky, but the first line table entry for a function 824 // points to the "{" that starts the function block. It would be nice to 825 // actually get the function declaration in there too. So back up a bit, 826 // but not further than what you're going to display. 827 uint32_t extra_lines; 828 if (m_options.num_lines >= 10) 829 extra_lines = 5; 830 else 831 extra_lines = m_options.num_lines / 2; 832 uint32_t line_no; 833 if (start_line <= extra_lines) 834 line_no = 1; 835 else 836 line_no = start_line - extra_lines; 837 838 // For fun, if the function is shorter than the number of lines we're 839 // supposed to display, only display the function... 840 if (end_line != 0) { 841 if (m_options.num_lines > end_line - line_no) 842 m_options.num_lines = end_line - line_no + extra_lines; 843 } 844 845 m_breakpoint_locations.Clear(); 846 847 if (m_options.show_bp_locs) { 848 const bool show_inlines = true; 849 m_breakpoint_locations.Reset(start_file, 0, show_inlines); 850 SearchFilterForUnconstrainedSearches target_search_filter( 851 m_exe_ctx.GetTargetSP()); 852 target_search_filter.Search(m_breakpoint_locations); 853 } 854 855 result.AppendMessageWithFormat("File: %s\n", 856 start_file.GetPath().c_str()); 857 // We don't care about the column here. 858 const uint32_t column = 0; 859 return target->GetSourceManager().DisplaySourceLinesWithLineNumbers( 860 start_file, line_no, column, 0, m_options.num_lines, "", 861 &result.GetOutputStream(), GetBreakpointLocations()); 862 } else { 863 result.AppendErrorWithFormat( 864 "Could not find function info for: \"%s\".\n", 865 m_options.symbol_name.c_str()); 866 } 867 return 0; 868 } 869 870 // From Jim: The FindMatchingFunctions / FindMatchingFunctionSymbols 871 // functions "take a possibly empty vector of strings which are names of 872 // modules, and run the two search functions on the subset of the full module 873 // list that matches the strings in the input vector". If we wanted to put 874 // these somewhere, there should probably be a module-filter-list that can be 875 // passed to the various ModuleList::Find* calls, which would either be a 876 // vector of string names or a ModuleSpecList. 877 void FindMatchingFunctions(Target *target, ConstString name, 878 SymbolContextList &sc_list) { 879 // Displaying the source for a symbol: 880 if (m_options.num_lines == 0) 881 m_options.num_lines = 10; 882 883 ModuleFunctionSearchOptions function_options; 884 function_options.include_symbols = true; 885 function_options.include_inlines = false; 886 887 const size_t num_modules = m_options.modules.size(); 888 if (num_modules > 0) { 889 ModuleList matching_modules; 890 for (size_t i = 0; i < num_modules; ++i) { 891 FileSpec module_file_spec(m_options.modules[i]); 892 if (module_file_spec) { 893 ModuleSpec module_spec(module_file_spec); 894 matching_modules.Clear(); 895 target->GetImages().FindModules(module_spec, matching_modules); 896 897 matching_modules.FindFunctions(name, eFunctionNameTypeAuto, 898 function_options, sc_list); 899 } 900 } 901 } else { 902 target->GetImages().FindFunctions(name, eFunctionNameTypeAuto, 903 function_options, sc_list); 904 } 905 } 906 907 void FindMatchingFunctionSymbols(Target *target, ConstString name, 908 SymbolContextList &sc_list) { 909 const size_t num_modules = m_options.modules.size(); 910 if (num_modules > 0) { 911 ModuleList matching_modules; 912 for (size_t i = 0; i < num_modules; ++i) { 913 FileSpec module_file_spec(m_options.modules[i]); 914 if (module_file_spec) { 915 ModuleSpec module_spec(module_file_spec); 916 matching_modules.Clear(); 917 target->GetImages().FindModules(module_spec, matching_modules); 918 matching_modules.FindFunctionSymbols(name, eFunctionNameTypeAuto, 919 sc_list); 920 } 921 } 922 } else { 923 target->GetImages().FindFunctionSymbols(name, eFunctionNameTypeAuto, 924 sc_list); 925 } 926 } 927 928 bool DoExecute(Args &command, CommandReturnObject &result) override { 929 const size_t argc = command.GetArgumentCount(); 930 931 if (argc != 0) { 932 result.AppendErrorWithFormat("'%s' takes no arguments, only flags.\n", 933 GetCommandName().str().c_str()); 934 return false; 935 } 936 937 Target *target = m_exe_ctx.GetTargetPtr(); 938 939 if (!m_options.symbol_name.empty()) { 940 SymbolContextList sc_list; 941 ConstString name(m_options.symbol_name.c_str()); 942 943 // Displaying the source for a symbol. Search for function named name. 944 FindMatchingFunctions(target, name, sc_list); 945 size_t num_matches = sc_list.GetSize(); 946 if (!num_matches) { 947 // If we didn't find any functions with that name, try searching for 948 // symbols that line up exactly with function addresses. 949 SymbolContextList sc_list_symbols; 950 FindMatchingFunctionSymbols(target, name, sc_list_symbols); 951 size_t num_symbol_matches = sc_list_symbols.GetSize(); 952 953 for (size_t i = 0; i < num_symbol_matches; i++) { 954 SymbolContext sc; 955 sc_list_symbols.GetContextAtIndex(i, sc); 956 if (sc.symbol && sc.symbol->ValueIsAddress()) { 957 const Address &base_address = sc.symbol->GetAddressRef(); 958 Function *function = base_address.CalculateSymbolContextFunction(); 959 if (function) { 960 sc_list.Append(SymbolContext(function)); 961 num_matches++; 962 break; 963 } 964 } 965 } 966 } 967 968 if (num_matches == 0) { 969 result.AppendErrorWithFormat("Could not find function named: \"%s\".\n", 970 m_options.symbol_name.c_str()); 971 return false; 972 } 973 974 if (num_matches > 1) { 975 std::set<SourceInfo> source_match_set; 976 977 bool displayed_something = false; 978 for (size_t i = 0; i < num_matches; i++) { 979 SymbolContext sc; 980 sc_list.GetContextAtIndex(i, sc); 981 SourceInfo source_info(sc.GetFunctionName(), 982 sc.GetFunctionStartLineEntry()); 983 984 if (source_info.IsValid()) { 985 if (source_match_set.find(source_info) == source_match_set.end()) { 986 source_match_set.insert(source_info); 987 if (DisplayFunctionSource(sc, source_info, result)) 988 displayed_something = true; 989 } 990 } 991 } 992 993 if (displayed_something) 994 result.SetStatus(eReturnStatusSuccessFinishResult); 995 else 996 result.SetStatus(eReturnStatusFailed); 997 } else { 998 SymbolContext sc; 999 sc_list.GetContextAtIndex(0, sc); 1000 SourceInfo source_info; 1001 1002 if (DisplayFunctionSource(sc, source_info, result)) { 1003 result.SetStatus(eReturnStatusSuccessFinishResult); 1004 } else { 1005 result.SetStatus(eReturnStatusFailed); 1006 } 1007 } 1008 return result.Succeeded(); 1009 } else if (m_options.address != LLDB_INVALID_ADDRESS) { 1010 Address so_addr; 1011 StreamString error_strm; 1012 SymbolContextList sc_list; 1013 1014 if (target->GetSectionLoadList().IsEmpty()) { 1015 // The target isn't loaded yet, we need to lookup the file address in 1016 // all modules 1017 const ModuleList &module_list = target->GetImages(); 1018 const size_t num_modules = module_list.GetSize(); 1019 for (size_t i = 0; i < num_modules; ++i) { 1020 ModuleSP module_sp(module_list.GetModuleAtIndex(i)); 1021 if (module_sp && 1022 module_sp->ResolveFileAddress(m_options.address, so_addr)) { 1023 SymbolContext sc; 1024 sc.Clear(true); 1025 if (module_sp->ResolveSymbolContextForAddress( 1026 so_addr, eSymbolContextEverything, sc) & 1027 eSymbolContextLineEntry) 1028 sc_list.Append(sc); 1029 } 1030 } 1031 1032 if (sc_list.GetSize() == 0) { 1033 result.AppendErrorWithFormat( 1034 "no modules have source information for file address 0x%" PRIx64 1035 ".\n", 1036 m_options.address); 1037 return false; 1038 } 1039 } else { 1040 // The target has some things loaded, resolve this address to a compile 1041 // unit + file + line and display 1042 if (target->GetSectionLoadList().ResolveLoadAddress(m_options.address, 1043 so_addr)) { 1044 ModuleSP module_sp(so_addr.GetModule()); 1045 if (module_sp) { 1046 SymbolContext sc; 1047 sc.Clear(true); 1048 if (module_sp->ResolveSymbolContextForAddress( 1049 so_addr, eSymbolContextEverything, sc) & 1050 eSymbolContextLineEntry) { 1051 sc_list.Append(sc); 1052 } else { 1053 so_addr.Dump(&error_strm, nullptr, 1054 Address::DumpStyleModuleWithFileAddress); 1055 result.AppendErrorWithFormat("address resolves to %s, but there " 1056 "is no line table information " 1057 "available for this address.\n", 1058 error_strm.GetData()); 1059 return false; 1060 } 1061 } 1062 } 1063 1064 if (sc_list.GetSize() == 0) { 1065 result.AppendErrorWithFormat( 1066 "no modules contain load address 0x%" PRIx64 ".\n", 1067 m_options.address); 1068 return false; 1069 } 1070 } 1071 uint32_t num_matches = sc_list.GetSize(); 1072 for (uint32_t i = 0; i < num_matches; ++i) { 1073 SymbolContext sc; 1074 sc_list.GetContextAtIndex(i, sc); 1075 if (sc.comp_unit) { 1076 if (m_options.show_bp_locs) { 1077 m_breakpoint_locations.Clear(); 1078 const bool show_inlines = true; 1079 m_breakpoint_locations.Reset(sc.comp_unit->GetPrimaryFile(), 0, 1080 show_inlines); 1081 SearchFilterForUnconstrainedSearches target_search_filter( 1082 target->shared_from_this()); 1083 target_search_filter.Search(m_breakpoint_locations); 1084 } 1085 1086 bool show_fullpaths = true; 1087 bool show_module = true; 1088 bool show_inlined_frames = true; 1089 const bool show_function_arguments = true; 1090 const bool show_function_name = true; 1091 sc.DumpStopContext(&result.GetOutputStream(), 1092 m_exe_ctx.GetBestExecutionContextScope(), 1093 sc.line_entry.range.GetBaseAddress(), 1094 show_fullpaths, show_module, show_inlined_frames, 1095 show_function_arguments, show_function_name); 1096 result.GetOutputStream().EOL(); 1097 1098 if (m_options.num_lines == 0) 1099 m_options.num_lines = 10; 1100 1101 size_t lines_to_back_up = 1102 m_options.num_lines >= 10 ? 5 : m_options.num_lines / 2; 1103 1104 const uint32_t column = 1105 (GetDebugger().GetStopShowColumn() != eStopShowColumnNone) 1106 ? sc.line_entry.column 1107 : 0; 1108 target->GetSourceManager().DisplaySourceLinesWithLineNumbers( 1109 sc.comp_unit->GetPrimaryFile(), sc.line_entry.line, column, 1110 lines_to_back_up, m_options.num_lines - lines_to_back_up, "->", 1111 &result.GetOutputStream(), GetBreakpointLocations()); 1112 result.SetStatus(eReturnStatusSuccessFinishResult); 1113 } 1114 } 1115 } else if (m_options.file_name.empty()) { 1116 // Last valid source manager context, or the current frame if no valid 1117 // last context in source manager. One little trick here, if you type the 1118 // exact same list command twice in a row, it is more likely because you 1119 // typed it once, then typed it again 1120 if (m_options.start_line == 0) { 1121 if (target->GetSourceManager().DisplayMoreWithLineNumbers( 1122 &result.GetOutputStream(), m_options.num_lines, 1123 m_options.reverse, GetBreakpointLocations())) { 1124 result.SetStatus(eReturnStatusSuccessFinishResult); 1125 } 1126 } else { 1127 if (m_options.num_lines == 0) 1128 m_options.num_lines = 10; 1129 1130 if (m_options.show_bp_locs) { 1131 SourceManager::FileSP last_file_sp( 1132 target->GetSourceManager().GetLastFile()); 1133 if (last_file_sp) { 1134 const bool show_inlines = true; 1135 m_breakpoint_locations.Reset(last_file_sp->GetFileSpec(), 0, 1136 show_inlines); 1137 SearchFilterForUnconstrainedSearches target_search_filter( 1138 target->shared_from_this()); 1139 target_search_filter.Search(m_breakpoint_locations); 1140 } 1141 } else 1142 m_breakpoint_locations.Clear(); 1143 1144 const uint32_t column = 0; 1145 if (target->GetSourceManager() 1146 .DisplaySourceLinesWithLineNumbersUsingLastFile( 1147 m_options.start_line, // Line to display 1148 m_options.num_lines, // Lines after line to 1149 UINT32_MAX, // Don't mark "line" 1150 column, 1151 "", // Don't mark "line" 1152 &result.GetOutputStream(), GetBreakpointLocations())) { 1153 result.SetStatus(eReturnStatusSuccessFinishResult); 1154 } 1155 } 1156 } else { 1157 const char *filename = m_options.file_name.c_str(); 1158 1159 bool check_inlines = false; 1160 SymbolContextList sc_list; 1161 size_t num_matches = 0; 1162 1163 if (!m_options.modules.empty()) { 1164 ModuleList matching_modules; 1165 for (size_t i = 0, e = m_options.modules.size(); i < e; ++i) { 1166 FileSpec module_file_spec(m_options.modules[i]); 1167 if (module_file_spec) { 1168 ModuleSpec module_spec(module_file_spec); 1169 matching_modules.Clear(); 1170 target->GetImages().FindModules(module_spec, matching_modules); 1171 num_matches += matching_modules.ResolveSymbolContextForFilePath( 1172 filename, 0, check_inlines, 1173 SymbolContextItem(eSymbolContextModule | 1174 eSymbolContextCompUnit), 1175 sc_list); 1176 } 1177 } 1178 } else { 1179 num_matches = target->GetImages().ResolveSymbolContextForFilePath( 1180 filename, 0, check_inlines, 1181 eSymbolContextModule | eSymbolContextCompUnit, sc_list); 1182 } 1183 1184 if (num_matches == 0) { 1185 result.AppendErrorWithFormat("Could not find source file \"%s\".\n", 1186 m_options.file_name.c_str()); 1187 return false; 1188 } 1189 1190 if (num_matches > 1) { 1191 bool got_multiple = false; 1192 CompileUnit *test_cu = nullptr; 1193 1194 for (unsigned i = 0; i < num_matches; i++) { 1195 SymbolContext sc; 1196 sc_list.GetContextAtIndex(i, sc); 1197 if (sc.comp_unit) { 1198 if (test_cu) { 1199 if (test_cu != sc.comp_unit) 1200 got_multiple = true; 1201 break; 1202 } else 1203 test_cu = sc.comp_unit; 1204 } 1205 } 1206 if (got_multiple) { 1207 result.AppendErrorWithFormat( 1208 "Multiple source files found matching: \"%s.\"\n", 1209 m_options.file_name.c_str()); 1210 return false; 1211 } 1212 } 1213 1214 SymbolContext sc; 1215 if (sc_list.GetContextAtIndex(0, sc)) { 1216 if (sc.comp_unit) { 1217 if (m_options.show_bp_locs) { 1218 const bool show_inlines = true; 1219 m_breakpoint_locations.Reset(sc.comp_unit->GetPrimaryFile(), 0, 1220 show_inlines); 1221 SearchFilterForUnconstrainedSearches target_search_filter( 1222 target->shared_from_this()); 1223 target_search_filter.Search(m_breakpoint_locations); 1224 } else 1225 m_breakpoint_locations.Clear(); 1226 1227 if (m_options.num_lines == 0) 1228 m_options.num_lines = 10; 1229 const uint32_t column = 0; 1230 target->GetSourceManager().DisplaySourceLinesWithLineNumbers( 1231 sc.comp_unit->GetPrimaryFile(), m_options.start_line, column, 0, 1232 m_options.num_lines, "", &result.GetOutputStream(), 1233 GetBreakpointLocations()); 1234 1235 result.SetStatus(eReturnStatusSuccessFinishResult); 1236 } else { 1237 result.AppendErrorWithFormat("No comp unit found for: \"%s.\"\n", 1238 m_options.file_name.c_str()); 1239 return false; 1240 } 1241 } 1242 } 1243 return result.Succeeded(); 1244 } 1245 1246 const SymbolContextList *GetBreakpointLocations() { 1247 if (m_breakpoint_locations.GetFileLineMatches().GetSize() > 0) 1248 return &m_breakpoint_locations.GetFileLineMatches(); 1249 return nullptr; 1250 } 1251 1252 CommandOptions m_options; 1253 FileLineResolver m_breakpoint_locations; 1254 std::string m_reverse_name; 1255 }; 1256 1257 #pragma mark CommandObjectMultiwordSource 1258 // CommandObjectMultiwordSource 1259 1260 CommandObjectMultiwordSource::CommandObjectMultiwordSource( 1261 CommandInterpreter &interpreter) 1262 : CommandObjectMultiword(interpreter, "source", 1263 "Commands for examining " 1264 "source code described by " 1265 "debug information for the " 1266 "current target process.", 1267 "source <subcommand> [<subcommand-options>]") { 1268 LoadSubCommand("info", 1269 CommandObjectSP(new CommandObjectSourceInfo(interpreter))); 1270 LoadSubCommand("list", 1271 CommandObjectSP(new CommandObjectSourceList(interpreter))); 1272 } 1273 1274 CommandObjectMultiwordSource::~CommandObjectMultiwordSource() = default; 1275