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