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