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