1 //===-- CommandObjectTarget.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 "CommandObjectTarget.h" 10 11 #include "lldb/Core/Debugger.h" 12 #include "lldb/Core/IOHandler.h" 13 #include "lldb/Core/Module.h" 14 #include "lldb/Core/ModuleSpec.h" 15 #include "lldb/Core/Section.h" 16 #include "lldb/Core/ValueObjectVariable.h" 17 #include "lldb/DataFormatters/ValueObjectPrinter.h" 18 #include "lldb/Host/OptionParser.h" 19 #include "lldb/Host/StringConvert.h" 20 #include "lldb/Interpreter/CommandInterpreter.h" 21 #include "lldb/Interpreter/CommandReturnObject.h" 22 #include "lldb/Interpreter/OptionArgParser.h" 23 #include "lldb/Interpreter/OptionGroupArchitecture.h" 24 #include "lldb/Interpreter/OptionGroupBoolean.h" 25 #include "lldb/Interpreter/OptionGroupFile.h" 26 #include "lldb/Interpreter/OptionGroupFormat.h" 27 #include "lldb/Interpreter/OptionGroupPlatform.h" 28 #include "lldb/Interpreter/OptionGroupString.h" 29 #include "lldb/Interpreter/OptionGroupUInt64.h" 30 #include "lldb/Interpreter/OptionGroupUUID.h" 31 #include "lldb/Interpreter/OptionGroupValueObjectDisplay.h" 32 #include "lldb/Interpreter/OptionGroupVariable.h" 33 #include "lldb/Interpreter/Options.h" 34 #include "lldb/Symbol/CompileUnit.h" 35 #include "lldb/Symbol/FuncUnwinders.h" 36 #include "lldb/Symbol/LineTable.h" 37 #include "lldb/Symbol/LocateSymbolFile.h" 38 #include "lldb/Symbol/ObjectFile.h" 39 #include "lldb/Symbol/SymbolFile.h" 40 #include "lldb/Symbol/SymbolVendor.h" 41 #include "lldb/Symbol/UnwindPlan.h" 42 #include "lldb/Symbol/VariableList.h" 43 #include "lldb/Target/ABI.h" 44 #include "lldb/Target/Process.h" 45 #include "lldb/Target/RegisterContext.h" 46 #include "lldb/Target/SectionLoadList.h" 47 #include "lldb/Target/StackFrame.h" 48 #include "lldb/Target/Thread.h" 49 #include "lldb/Target/ThreadSpec.h" 50 #include "lldb/Utility/Args.h" 51 #include "lldb/Utility/State.h" 52 #include "lldb/Utility/Timer.h" 53 54 #include "llvm/Support/FileSystem.h" 55 #include "llvm/Support/FormatAdapters.h" 56 57 #include <cerrno> 58 59 using namespace lldb; 60 using namespace lldb_private; 61 62 static void DumpTargetInfo(uint32_t target_idx, Target *target, 63 const char *prefix_cstr, 64 bool show_stopped_process_status, Stream &strm) { 65 const ArchSpec &target_arch = target->GetArchitecture(); 66 67 Module *exe_module = target->GetExecutableModulePointer(); 68 char exe_path[PATH_MAX]; 69 bool exe_valid = false; 70 if (exe_module) 71 exe_valid = exe_module->GetFileSpec().GetPath(exe_path, sizeof(exe_path)); 72 73 if (!exe_valid) 74 ::strcpy(exe_path, "<none>"); 75 76 strm.Printf("%starget #%u: %s", prefix_cstr ? prefix_cstr : "", target_idx, 77 exe_path); 78 79 uint32_t properties = 0; 80 if (target_arch.IsValid()) { 81 strm.Printf("%sarch=", properties++ > 0 ? ", " : " ( "); 82 target_arch.DumpTriple(strm); 83 properties++; 84 } 85 PlatformSP platform_sp(target->GetPlatform()); 86 if (platform_sp) 87 strm.Printf("%splatform=%s", properties++ > 0 ? ", " : " ( ", 88 platform_sp->GetName().GetCString()); 89 90 ProcessSP process_sp(target->GetProcessSP()); 91 bool show_process_status = false; 92 if (process_sp) { 93 lldb::pid_t pid = process_sp->GetID(); 94 StateType state = process_sp->GetState(); 95 if (show_stopped_process_status) 96 show_process_status = StateIsStoppedState(state, true); 97 const char *state_cstr = StateAsCString(state); 98 if (pid != LLDB_INVALID_PROCESS_ID) 99 strm.Printf("%spid=%" PRIu64, properties++ > 0 ? ", " : " ( ", pid); 100 strm.Printf("%sstate=%s", properties++ > 0 ? ", " : " ( ", state_cstr); 101 } 102 if (properties > 0) 103 strm.PutCString(" )\n"); 104 else 105 strm.EOL(); 106 if (show_process_status) { 107 const bool only_threads_with_stop_reason = true; 108 const uint32_t start_frame = 0; 109 const uint32_t num_frames = 1; 110 const uint32_t num_frames_with_source = 1; 111 const bool stop_format = false; 112 process_sp->GetStatus(strm); 113 process_sp->GetThreadStatus(strm, only_threads_with_stop_reason, 114 start_frame, num_frames, 115 num_frames_with_source, stop_format); 116 } 117 } 118 119 static uint32_t DumpTargetList(TargetList &target_list, 120 bool show_stopped_process_status, Stream &strm) { 121 const uint32_t num_targets = target_list.GetNumTargets(); 122 if (num_targets) { 123 TargetSP selected_target_sp(target_list.GetSelectedTarget()); 124 strm.PutCString("Current targets:\n"); 125 for (uint32_t i = 0; i < num_targets; ++i) { 126 TargetSP target_sp(target_list.GetTargetAtIndex(i)); 127 if (target_sp) { 128 bool is_selected = target_sp.get() == selected_target_sp.get(); 129 DumpTargetInfo(i, target_sp.get(), is_selected ? "* " : " ", 130 show_stopped_process_status, strm); 131 } 132 } 133 } 134 return num_targets; 135 } 136 137 // Note that the negation in the argument name causes a slightly confusing 138 // mapping of the enum values. 139 static constexpr OptionEnumValueElement g_dependents_enumaration[] = { 140 { 141 eLoadDependentsDefault, 142 "default", 143 "Only load dependents when the target is an executable.", 144 }, 145 { 146 eLoadDependentsNo, 147 "true", 148 "Don't load dependents, even if the target is an executable.", 149 }, 150 { 151 eLoadDependentsYes, 152 "false", 153 "Load dependents, even if the target is not an executable.", 154 }, 155 }; 156 157 #define LLDB_OPTIONS_target_dependents 158 #include "CommandOptions.inc" 159 160 class OptionGroupDependents : public OptionGroup { 161 public: 162 OptionGroupDependents() {} 163 164 ~OptionGroupDependents() override {} 165 166 llvm::ArrayRef<OptionDefinition> GetDefinitions() override { 167 return llvm::makeArrayRef(g_target_dependents_options); 168 } 169 170 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value, 171 ExecutionContext *execution_context) override { 172 Status error; 173 174 // For compatibility no value means don't load dependents. 175 if (option_value.empty()) { 176 m_load_dependent_files = eLoadDependentsNo; 177 return error; 178 } 179 180 const char short_option = 181 g_target_dependents_options[option_idx].short_option; 182 if (short_option == 'd') { 183 LoadDependentFiles tmp_load_dependents; 184 tmp_load_dependents = (LoadDependentFiles)OptionArgParser::ToOptionEnum( 185 option_value, g_target_dependents_options[option_idx].enum_values, 0, 186 error); 187 if (error.Success()) 188 m_load_dependent_files = tmp_load_dependents; 189 } else { 190 error.SetErrorStringWithFormat("unrecognized short option '%c'", 191 short_option); 192 } 193 194 return error; 195 } 196 197 Status SetOptionValue(uint32_t, const char *, ExecutionContext *) = delete; 198 199 void OptionParsingStarting(ExecutionContext *execution_context) override { 200 m_load_dependent_files = eLoadDependentsDefault; 201 } 202 203 LoadDependentFiles m_load_dependent_files; 204 205 private: 206 DISALLOW_COPY_AND_ASSIGN(OptionGroupDependents); 207 }; 208 209 #pragma mark CommandObjectTargetCreate 210 211 // "target create" 212 213 class CommandObjectTargetCreate : public CommandObjectParsed { 214 public: 215 CommandObjectTargetCreate(CommandInterpreter &interpreter) 216 : CommandObjectParsed( 217 interpreter, "target create", 218 "Create a target using the argument as the main executable.", 219 nullptr), 220 m_option_group(), m_arch_option(), 221 m_core_file(LLDB_OPT_SET_1, false, "core", 'c', 0, eArgTypeFilename, 222 "Fullpath to a core file to use for this target."), 223 m_platform_path(LLDB_OPT_SET_1, false, "platform-path", 'P', 0, 224 eArgTypePath, 225 "Path to the remote file to use for this target."), 226 m_symbol_file(LLDB_OPT_SET_1, false, "symfile", 's', 0, 227 eArgTypeFilename, 228 "Fullpath to a stand alone debug " 229 "symbols file for when debug symbols " 230 "are not in the executable."), 231 m_remote_file( 232 LLDB_OPT_SET_1, false, "remote-file", 'r', 0, eArgTypeFilename, 233 "Fullpath to the file on the remote host if debugging remotely."), 234 m_add_dependents() { 235 CommandArgumentEntry arg; 236 CommandArgumentData file_arg; 237 238 // Define the first (and only) variant of this arg. 239 file_arg.arg_type = eArgTypeFilename; 240 file_arg.arg_repetition = eArgRepeatPlain; 241 242 // There is only one variant this argument could be; put it into the 243 // argument entry. 244 arg.push_back(file_arg); 245 246 // Push the data for the first argument into the m_arguments vector. 247 m_arguments.push_back(arg); 248 249 m_option_group.Append(&m_arch_option, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); 250 m_option_group.Append(&m_core_file, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); 251 m_option_group.Append(&m_platform_path, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); 252 m_option_group.Append(&m_symbol_file, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); 253 m_option_group.Append(&m_remote_file, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); 254 m_option_group.Append(&m_add_dependents, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); 255 m_option_group.Finalize(); 256 } 257 258 ~CommandObjectTargetCreate() override = default; 259 260 Options *GetOptions() override { return &m_option_group; } 261 262 int HandleArgumentCompletion( 263 CompletionRequest &request, 264 OptionElementVector &opt_element_vector) override { 265 CommandCompletions::InvokeCommonCompletionCallbacks( 266 GetCommandInterpreter(), CommandCompletions::eDiskFileCompletion, 267 request, nullptr); 268 return request.GetNumberOfMatches(); 269 } 270 271 protected: 272 bool DoExecute(Args &command, CommandReturnObject &result) override { 273 const size_t argc = command.GetArgumentCount(); 274 FileSpec core_file(m_core_file.GetOptionValue().GetCurrentValue()); 275 FileSpec remote_file(m_remote_file.GetOptionValue().GetCurrentValue()); 276 277 if (core_file) { 278 if (!FileSystem::Instance().Exists(core_file)) { 279 result.AppendErrorWithFormat("core file '%s' doesn't exist", 280 core_file.GetPath().c_str()); 281 result.SetStatus(eReturnStatusFailed); 282 return false; 283 } 284 if (!FileSystem::Instance().Readable(core_file)) { 285 result.AppendErrorWithFormat("core file '%s' is not readable", 286 core_file.GetPath().c_str()); 287 result.SetStatus(eReturnStatusFailed); 288 return false; 289 } 290 } 291 292 if (argc == 1 || core_file || remote_file) { 293 FileSpec symfile(m_symbol_file.GetOptionValue().GetCurrentValue()); 294 if (symfile) { 295 if (FileSystem::Instance().Exists(symfile)) { 296 if (!FileSystem::Instance().Readable(symfile)) { 297 result.AppendErrorWithFormat("symbol file '%s' is not readable", 298 symfile.GetPath().c_str()); 299 result.SetStatus(eReturnStatusFailed); 300 return false; 301 } 302 } else { 303 char symfile_path[PATH_MAX]; 304 symfile.GetPath(symfile_path, sizeof(symfile_path)); 305 result.AppendErrorWithFormat("invalid symbol file path '%s'", 306 symfile_path); 307 result.SetStatus(eReturnStatusFailed); 308 return false; 309 } 310 } 311 312 const char *file_path = command.GetArgumentAtIndex(0); 313 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); 314 Timer scoped_timer(func_cat, "(lldb) target create '%s'", file_path); 315 FileSpec file_spec; 316 317 if (file_path) { 318 file_spec.SetFile(file_path, FileSpec::Style::native); 319 FileSystem::Instance().Resolve(file_spec); 320 } 321 322 bool must_set_platform_path = false; 323 324 Debugger &debugger = GetDebugger(); 325 326 TargetSP target_sp; 327 llvm::StringRef arch_cstr = m_arch_option.GetArchitectureName(); 328 Status error(debugger.GetTargetList().CreateTarget( 329 debugger, file_path, arch_cstr, 330 m_add_dependents.m_load_dependent_files, nullptr, target_sp)); 331 332 if (target_sp) { 333 // Only get the platform after we create the target because we might 334 // have switched platforms depending on what the arguments were to 335 // CreateTarget() we can't rely on the selected platform. 336 337 PlatformSP platform_sp = target_sp->GetPlatform(); 338 339 if (remote_file) { 340 if (platform_sp) { 341 // I have a remote file.. two possible cases 342 if (file_spec && FileSystem::Instance().Exists(file_spec)) { 343 // if the remote file does not exist, push it there 344 if (!platform_sp->GetFileExists(remote_file)) { 345 Status err = platform_sp->PutFile(file_spec, remote_file); 346 if (err.Fail()) { 347 result.AppendError(err.AsCString()); 348 result.SetStatus(eReturnStatusFailed); 349 return false; 350 } 351 } 352 } else { 353 // there is no local file and we need one 354 // in order to make the remote ---> local transfer we need a 355 // platform 356 // TODO: if the user has passed in a --platform argument, use it 357 // to fetch the right platform 358 if (!platform_sp) { 359 result.AppendError( 360 "unable to perform remote debugging without a platform"); 361 result.SetStatus(eReturnStatusFailed); 362 return false; 363 } 364 if (file_path) { 365 // copy the remote file to the local file 366 Status err = platform_sp->GetFile(remote_file, file_spec); 367 if (err.Fail()) { 368 result.AppendError(err.AsCString()); 369 result.SetStatus(eReturnStatusFailed); 370 return false; 371 } 372 } else { 373 // make up a local file 374 result.AppendError("remote --> local transfer without local " 375 "path is not implemented yet"); 376 result.SetStatus(eReturnStatusFailed); 377 return false; 378 } 379 } 380 } else { 381 result.AppendError("no platform found for target"); 382 result.SetStatus(eReturnStatusFailed); 383 return false; 384 } 385 } 386 387 if (symfile || remote_file) { 388 ModuleSP module_sp(target_sp->GetExecutableModule()); 389 if (module_sp) { 390 if (symfile) 391 module_sp->SetSymbolFileFileSpec(symfile); 392 if (remote_file) { 393 std::string remote_path = remote_file.GetPath(); 394 target_sp->SetArg0(remote_path.c_str()); 395 module_sp->SetPlatformFileSpec(remote_file); 396 } 397 } 398 } 399 400 debugger.GetTargetList().SetSelectedTarget(target_sp.get()); 401 if (must_set_platform_path) { 402 ModuleSpec main_module_spec(file_spec); 403 ModuleSP module_sp = target_sp->GetOrCreateModule(main_module_spec, 404 true /* notify */); 405 if (module_sp) 406 module_sp->SetPlatformFileSpec(remote_file); 407 } 408 if (core_file) { 409 char core_path[PATH_MAX]; 410 core_file.GetPath(core_path, sizeof(core_path)); 411 if (FileSystem::Instance().Exists(core_file)) { 412 if (!FileSystem::Instance().Readable(core_file)) { 413 result.AppendMessageWithFormat( 414 "Core file '%s' is not readable.\n", core_path); 415 result.SetStatus(eReturnStatusFailed); 416 return false; 417 } 418 FileSpec core_file_dir; 419 core_file_dir.GetDirectory() = core_file.GetDirectory(); 420 target_sp->AppendExecutableSearchPaths(core_file_dir); 421 422 ProcessSP process_sp(target_sp->CreateProcess( 423 GetDebugger().GetListener(), llvm::StringRef(), &core_file)); 424 425 if (process_sp) { 426 // Seems weird that we Launch a core file, but that is what we 427 // do! 428 error = process_sp->LoadCore(); 429 430 if (error.Fail()) { 431 result.AppendError( 432 error.AsCString("can't find plug-in for core file")); 433 result.SetStatus(eReturnStatusFailed); 434 return false; 435 } else { 436 result.AppendMessageWithFormat( 437 "Core file '%s' (%s) was loaded.\n", core_path, 438 target_sp->GetArchitecture().GetArchitectureName()); 439 result.SetStatus(eReturnStatusSuccessFinishNoResult); 440 } 441 } else { 442 result.AppendErrorWithFormat( 443 "Unable to find process plug-in for core file '%s'\n", 444 core_path); 445 result.SetStatus(eReturnStatusFailed); 446 } 447 } else { 448 result.AppendErrorWithFormat("Core file '%s' does not exist\n", 449 core_path); 450 result.SetStatus(eReturnStatusFailed); 451 } 452 } else { 453 result.AppendMessageWithFormat( 454 "Current executable set to '%s' (%s).\n", file_path, 455 target_sp->GetArchitecture().GetArchitectureName()); 456 result.SetStatus(eReturnStatusSuccessFinishNoResult); 457 } 458 } else { 459 result.AppendError(error.AsCString()); 460 result.SetStatus(eReturnStatusFailed); 461 } 462 } else { 463 result.AppendErrorWithFormat("'%s' takes exactly one executable path " 464 "argument, or use the --core option.\n", 465 m_cmd_name.c_str()); 466 result.SetStatus(eReturnStatusFailed); 467 } 468 return result.Succeeded(); 469 } 470 471 private: 472 OptionGroupOptions m_option_group; 473 OptionGroupArchitecture m_arch_option; 474 OptionGroupFile m_core_file; 475 OptionGroupFile m_platform_path; 476 OptionGroupFile m_symbol_file; 477 OptionGroupFile m_remote_file; 478 OptionGroupDependents m_add_dependents; 479 }; 480 481 #pragma mark CommandObjectTargetList 482 483 // "target list" 484 485 class CommandObjectTargetList : public CommandObjectParsed { 486 public: 487 CommandObjectTargetList(CommandInterpreter &interpreter) 488 : CommandObjectParsed( 489 interpreter, "target list", 490 "List all current targets in the current debug session.", nullptr) { 491 } 492 493 ~CommandObjectTargetList() override = default; 494 495 protected: 496 bool DoExecute(Args &args, CommandReturnObject &result) override { 497 if (args.GetArgumentCount() == 0) { 498 Stream &strm = result.GetOutputStream(); 499 500 bool show_stopped_process_status = false; 501 if (DumpTargetList(GetDebugger().GetTargetList(), 502 show_stopped_process_status, strm) == 0) { 503 strm.PutCString("No targets.\n"); 504 } 505 result.SetStatus(eReturnStatusSuccessFinishResult); 506 } else { 507 result.AppendError("the 'target list' command takes no arguments\n"); 508 result.SetStatus(eReturnStatusFailed); 509 } 510 return result.Succeeded(); 511 } 512 }; 513 514 #pragma mark CommandObjectTargetSelect 515 516 // "target select" 517 518 class CommandObjectTargetSelect : public CommandObjectParsed { 519 public: 520 CommandObjectTargetSelect(CommandInterpreter &interpreter) 521 : CommandObjectParsed( 522 interpreter, "target select", 523 "Select a target as the current target by target index.", nullptr) { 524 } 525 526 ~CommandObjectTargetSelect() override = default; 527 528 protected: 529 bool DoExecute(Args &args, CommandReturnObject &result) override { 530 if (args.GetArgumentCount() == 1) { 531 bool success = false; 532 const char *target_idx_arg = args.GetArgumentAtIndex(0); 533 uint32_t target_idx = 534 StringConvert::ToUInt32(target_idx_arg, UINT32_MAX, 0, &success); 535 if (success) { 536 TargetList &target_list = GetDebugger().GetTargetList(); 537 const uint32_t num_targets = target_list.GetNumTargets(); 538 if (target_idx < num_targets) { 539 TargetSP target_sp(target_list.GetTargetAtIndex(target_idx)); 540 if (target_sp) { 541 Stream &strm = result.GetOutputStream(); 542 target_list.SetSelectedTarget(target_sp.get()); 543 bool show_stopped_process_status = false; 544 DumpTargetList(target_list, show_stopped_process_status, strm); 545 result.SetStatus(eReturnStatusSuccessFinishResult); 546 } else { 547 result.AppendErrorWithFormat("target #%u is NULL in target list\n", 548 target_idx); 549 result.SetStatus(eReturnStatusFailed); 550 } 551 } else { 552 if (num_targets > 0) { 553 result.AppendErrorWithFormat( 554 "index %u is out of range, valid target indexes are 0 - %u\n", 555 target_idx, num_targets - 1); 556 } else { 557 result.AppendErrorWithFormat( 558 "index %u is out of range since there are no active targets\n", 559 target_idx); 560 } 561 result.SetStatus(eReturnStatusFailed); 562 } 563 } else { 564 result.AppendErrorWithFormat("invalid index string value '%s'\n", 565 target_idx_arg); 566 result.SetStatus(eReturnStatusFailed); 567 } 568 } else { 569 result.AppendError( 570 "'target select' takes a single argument: a target index\n"); 571 result.SetStatus(eReturnStatusFailed); 572 } 573 return result.Succeeded(); 574 } 575 }; 576 577 #pragma mark CommandObjectTargetSelect 578 579 // "target delete" 580 581 class CommandObjectTargetDelete : public CommandObjectParsed { 582 public: 583 CommandObjectTargetDelete(CommandInterpreter &interpreter) 584 : CommandObjectParsed(interpreter, "target delete", 585 "Delete one or more targets by target index.", 586 nullptr), 587 m_option_group(), m_all_option(LLDB_OPT_SET_1, false, "all", 'a', 588 "Delete all targets.", false, true), 589 m_cleanup_option( 590 LLDB_OPT_SET_1, false, "clean", 'c', 591 "Perform extra cleanup to minimize memory consumption after " 592 "deleting the target. " 593 "By default, LLDB will keep in memory any modules previously " 594 "loaded by the target as well " 595 "as all of its debug info. Specifying --clean will unload all of " 596 "these shared modules and " 597 "cause them to be reparsed again the next time the target is run", 598 false, true) { 599 m_option_group.Append(&m_all_option, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); 600 m_option_group.Append(&m_cleanup_option, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); 601 m_option_group.Finalize(); 602 } 603 604 ~CommandObjectTargetDelete() override = default; 605 606 Options *GetOptions() override { return &m_option_group; } 607 608 protected: 609 bool DoExecute(Args &args, CommandReturnObject &result) override { 610 const size_t argc = args.GetArgumentCount(); 611 std::vector<TargetSP> delete_target_list; 612 TargetList &target_list = GetDebugger().GetTargetList(); 613 TargetSP target_sp; 614 615 if (m_all_option.GetOptionValue()) { 616 for (int i = 0; i < target_list.GetNumTargets(); ++i) 617 delete_target_list.push_back(target_list.GetTargetAtIndex(i)); 618 } else if (argc > 0) { 619 const uint32_t num_targets = target_list.GetNumTargets(); 620 // Bail out if don't have any targets. 621 if (num_targets == 0) { 622 result.AppendError("no targets to delete"); 623 result.SetStatus(eReturnStatusFailed); 624 return false; 625 } 626 627 for (auto &entry : args.entries()) { 628 uint32_t target_idx; 629 if (entry.ref.getAsInteger(0, target_idx)) { 630 result.AppendErrorWithFormat("invalid target index '%s'\n", 631 entry.c_str()); 632 result.SetStatus(eReturnStatusFailed); 633 return false; 634 } 635 if (target_idx < num_targets) { 636 target_sp = target_list.GetTargetAtIndex(target_idx); 637 if (target_sp) { 638 delete_target_list.push_back(target_sp); 639 continue; 640 } 641 } 642 if (num_targets > 1) 643 result.AppendErrorWithFormat("target index %u is out of range, valid " 644 "target indexes are 0 - %u\n", 645 target_idx, num_targets - 1); 646 else 647 result.AppendErrorWithFormat( 648 "target index %u is out of range, the only valid index is 0\n", 649 target_idx); 650 651 result.SetStatus(eReturnStatusFailed); 652 return false; 653 } 654 } else { 655 target_sp = target_list.GetSelectedTarget(); 656 if (!target_sp) { 657 result.AppendErrorWithFormat("no target is currently selected\n"); 658 result.SetStatus(eReturnStatusFailed); 659 return false; 660 } 661 delete_target_list.push_back(target_sp); 662 } 663 664 const size_t num_targets_to_delete = delete_target_list.size(); 665 for (size_t idx = 0; idx < num_targets_to_delete; ++idx) { 666 target_sp = delete_target_list[idx]; 667 target_list.DeleteTarget(target_sp); 668 target_sp->Destroy(); 669 } 670 // If "--clean" was specified, prune any orphaned shared modules from the 671 // global shared module list 672 if (m_cleanup_option.GetOptionValue()) { 673 const bool mandatory = true; 674 ModuleList::RemoveOrphanSharedModules(mandatory); 675 } 676 result.GetOutputStream().Printf("%u targets deleted.\n", 677 (uint32_t)num_targets_to_delete); 678 result.SetStatus(eReturnStatusSuccessFinishResult); 679 680 return true; 681 } 682 683 OptionGroupOptions m_option_group; 684 OptionGroupBoolean m_all_option; 685 OptionGroupBoolean m_cleanup_option; 686 }; 687 688 #pragma mark CommandObjectTargetVariable 689 690 // "target variable" 691 692 class CommandObjectTargetVariable : public CommandObjectParsed { 693 static const uint32_t SHORT_OPTION_FILE = 0x66696c65; // 'file' 694 static const uint32_t SHORT_OPTION_SHLB = 0x73686c62; // 'shlb' 695 696 public: 697 CommandObjectTargetVariable(CommandInterpreter &interpreter) 698 : CommandObjectParsed(interpreter, "target variable", 699 "Read global variables for the current target, " 700 "before or while running a process.", 701 nullptr, eCommandRequiresTarget), 702 m_option_group(), 703 m_option_variable(false), // Don't include frame options 704 m_option_format(eFormatDefault), 705 m_option_compile_units(LLDB_OPT_SET_1, false, "file", SHORT_OPTION_FILE, 706 0, eArgTypeFilename, 707 "A basename or fullpath to a file that contains " 708 "global variables. This option can be " 709 "specified multiple times."), 710 m_option_shared_libraries( 711 LLDB_OPT_SET_1, false, "shlib", SHORT_OPTION_SHLB, 0, 712 eArgTypeFilename, 713 "A basename or fullpath to a shared library to use in the search " 714 "for global " 715 "variables. This option can be specified multiple times."), 716 m_varobj_options() { 717 CommandArgumentEntry arg; 718 CommandArgumentData var_name_arg; 719 720 // Define the first (and only) variant of this arg. 721 var_name_arg.arg_type = eArgTypeVarName; 722 var_name_arg.arg_repetition = eArgRepeatPlus; 723 724 // There is only one variant this argument could be; put it into the 725 // argument entry. 726 arg.push_back(var_name_arg); 727 728 // Push the data for the first argument into the m_arguments vector. 729 m_arguments.push_back(arg); 730 731 m_option_group.Append(&m_varobj_options, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); 732 m_option_group.Append(&m_option_variable, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); 733 m_option_group.Append(&m_option_format, 734 OptionGroupFormat::OPTION_GROUP_FORMAT | 735 OptionGroupFormat::OPTION_GROUP_GDB_FMT, 736 LLDB_OPT_SET_1); 737 m_option_group.Append(&m_option_compile_units, LLDB_OPT_SET_ALL, 738 LLDB_OPT_SET_1); 739 m_option_group.Append(&m_option_shared_libraries, LLDB_OPT_SET_ALL, 740 LLDB_OPT_SET_1); 741 m_option_group.Finalize(); 742 } 743 744 ~CommandObjectTargetVariable() override = default; 745 746 void DumpValueObject(Stream &s, VariableSP &var_sp, ValueObjectSP &valobj_sp, 747 const char *root_name) { 748 DumpValueObjectOptions options(m_varobj_options.GetAsDumpOptions()); 749 750 if (!valobj_sp->GetTargetSP()->GetDisplayRuntimeSupportValues() && 751 valobj_sp->IsRuntimeSupportValue()) 752 return; 753 754 switch (var_sp->GetScope()) { 755 case eValueTypeVariableGlobal: 756 if (m_option_variable.show_scope) 757 s.PutCString("GLOBAL: "); 758 break; 759 760 case eValueTypeVariableStatic: 761 if (m_option_variable.show_scope) 762 s.PutCString("STATIC: "); 763 break; 764 765 case eValueTypeVariableArgument: 766 if (m_option_variable.show_scope) 767 s.PutCString(" ARG: "); 768 break; 769 770 case eValueTypeVariableLocal: 771 if (m_option_variable.show_scope) 772 s.PutCString(" LOCAL: "); 773 break; 774 775 case eValueTypeVariableThreadLocal: 776 if (m_option_variable.show_scope) 777 s.PutCString("THREAD: "); 778 break; 779 780 default: 781 break; 782 } 783 784 if (m_option_variable.show_decl) { 785 bool show_fullpaths = false; 786 bool show_module = true; 787 if (var_sp->DumpDeclaration(&s, show_fullpaths, show_module)) 788 s.PutCString(": "); 789 } 790 791 const Format format = m_option_format.GetFormat(); 792 if (format != eFormatDefault) 793 options.SetFormat(format); 794 795 options.SetRootValueObjectName(root_name); 796 797 valobj_sp->Dump(s, options); 798 } 799 800 static size_t GetVariableCallback(void *baton, const char *name, 801 VariableList &variable_list) { 802 Target *target = static_cast<Target *>(baton); 803 if (target) { 804 return target->GetImages().FindGlobalVariables(ConstString(name), 805 UINT32_MAX, variable_list); 806 } 807 return 0; 808 } 809 810 Options *GetOptions() override { return &m_option_group; } 811 812 protected: 813 void DumpGlobalVariableList(const ExecutionContext &exe_ctx, 814 const SymbolContext &sc, 815 const VariableList &variable_list, Stream &s) { 816 size_t count = variable_list.GetSize(); 817 if (count > 0) { 818 if (sc.module_sp) { 819 if (sc.comp_unit) { 820 s.Printf("Global variables for %s in %s:\n", 821 sc.comp_unit->GetPath().c_str(), 822 sc.module_sp->GetFileSpec().GetPath().c_str()); 823 } else { 824 s.Printf("Global variables for %s\n", 825 sc.module_sp->GetFileSpec().GetPath().c_str()); 826 } 827 } else if (sc.comp_unit) { 828 s.Printf("Global variables for %s\n", sc.comp_unit->GetPath().c_str()); 829 } 830 831 for (uint32_t i = 0; i < count; ++i) { 832 VariableSP var_sp(variable_list.GetVariableAtIndex(i)); 833 if (var_sp) { 834 ValueObjectSP valobj_sp(ValueObjectVariable::Create( 835 exe_ctx.GetBestExecutionContextScope(), var_sp)); 836 837 if (valobj_sp) 838 DumpValueObject(s, var_sp, valobj_sp, 839 var_sp->GetName().GetCString()); 840 } 841 } 842 } 843 } 844 845 bool DoExecute(Args &args, CommandReturnObject &result) override { 846 Target *target = m_exe_ctx.GetTargetPtr(); 847 const size_t argc = args.GetArgumentCount(); 848 Stream &s = result.GetOutputStream(); 849 850 if (argc > 0) { 851 852 // TODO: Convert to entry-based iteration. Requires converting 853 // DumpValueObject. 854 for (size_t idx = 0; idx < argc; ++idx) { 855 VariableList variable_list; 856 ValueObjectList valobj_list; 857 858 const char *arg = args.GetArgumentAtIndex(idx); 859 size_t matches = 0; 860 bool use_var_name = false; 861 if (m_option_variable.use_regex) { 862 RegularExpression regex(llvm::StringRef::withNullAsEmpty(arg)); 863 if (!regex.IsValid()) { 864 result.GetErrorStream().Printf( 865 "error: invalid regular expression: '%s'\n", arg); 866 result.SetStatus(eReturnStatusFailed); 867 return false; 868 } 869 use_var_name = true; 870 matches = target->GetImages().FindGlobalVariables(regex, UINT32_MAX, 871 variable_list); 872 } else { 873 Status error(Variable::GetValuesForVariableExpressionPath( 874 arg, m_exe_ctx.GetBestExecutionContextScope(), 875 GetVariableCallback, target, variable_list, valobj_list)); 876 matches = variable_list.GetSize(); 877 } 878 879 if (matches == 0) { 880 result.GetErrorStream().Printf( 881 "error: can't find global variable '%s'\n", arg); 882 result.SetStatus(eReturnStatusFailed); 883 return false; 884 } else { 885 for (uint32_t global_idx = 0; global_idx < matches; ++global_idx) { 886 VariableSP var_sp(variable_list.GetVariableAtIndex(global_idx)); 887 if (var_sp) { 888 ValueObjectSP valobj_sp( 889 valobj_list.GetValueObjectAtIndex(global_idx)); 890 if (!valobj_sp) 891 valobj_sp = ValueObjectVariable::Create( 892 m_exe_ctx.GetBestExecutionContextScope(), var_sp); 893 894 if (valobj_sp) 895 DumpValueObject(s, var_sp, valobj_sp, 896 use_var_name ? var_sp->GetName().GetCString() 897 : arg); 898 } 899 } 900 } 901 } 902 } else { 903 const FileSpecList &compile_units = 904 m_option_compile_units.GetOptionValue().GetCurrentValue(); 905 const FileSpecList &shlibs = 906 m_option_shared_libraries.GetOptionValue().GetCurrentValue(); 907 SymbolContextList sc_list; 908 const size_t num_compile_units = compile_units.GetSize(); 909 const size_t num_shlibs = shlibs.GetSize(); 910 if (num_compile_units == 0 && num_shlibs == 0) { 911 bool success = false; 912 StackFrame *frame = m_exe_ctx.GetFramePtr(); 913 CompileUnit *comp_unit = nullptr; 914 if (frame) { 915 SymbolContext sc = frame->GetSymbolContext(eSymbolContextCompUnit); 916 if (sc.comp_unit) { 917 const bool can_create = true; 918 VariableListSP comp_unit_varlist_sp( 919 sc.comp_unit->GetVariableList(can_create)); 920 if (comp_unit_varlist_sp) { 921 size_t count = comp_unit_varlist_sp->GetSize(); 922 if (count > 0) { 923 DumpGlobalVariableList(m_exe_ctx, sc, *comp_unit_varlist_sp, s); 924 success = true; 925 } 926 } 927 } 928 } 929 if (!success) { 930 if (frame) { 931 if (comp_unit) 932 result.AppendErrorWithFormat( 933 "no global variables in current compile unit: %s\n", 934 comp_unit->GetPath().c_str()); 935 else 936 result.AppendErrorWithFormat( 937 "no debug information for frame %u\n", 938 frame->GetFrameIndex()); 939 } else 940 result.AppendError("'target variable' takes one or more global " 941 "variable names as arguments\n"); 942 result.SetStatus(eReturnStatusFailed); 943 } 944 } else { 945 SymbolContextList sc_list; 946 const bool append = true; 947 // We have one or more compile unit or shlib 948 if (num_shlibs > 0) { 949 for (size_t shlib_idx = 0; shlib_idx < num_shlibs; ++shlib_idx) { 950 const FileSpec module_file(shlibs.GetFileSpecAtIndex(shlib_idx)); 951 ModuleSpec module_spec(module_file); 952 953 ModuleSP module_sp( 954 target->GetImages().FindFirstModule(module_spec)); 955 if (module_sp) { 956 if (num_compile_units > 0) { 957 for (size_t cu_idx = 0; cu_idx < num_compile_units; ++cu_idx) 958 module_sp->FindCompileUnits( 959 compile_units.GetFileSpecAtIndex(cu_idx), append, 960 sc_list); 961 } else { 962 SymbolContext sc; 963 sc.module_sp = module_sp; 964 sc_list.Append(sc); 965 } 966 } else { 967 // Didn't find matching shlib/module in target... 968 result.AppendErrorWithFormat( 969 "target doesn't contain the specified shared library: %s\n", 970 module_file.GetPath().c_str()); 971 } 972 } 973 } else { 974 // No shared libraries, we just want to find globals for the compile 975 // units files that were specified 976 for (size_t cu_idx = 0; cu_idx < num_compile_units; ++cu_idx) 977 target->GetImages().FindCompileUnits( 978 compile_units.GetFileSpecAtIndex(cu_idx), append, sc_list); 979 } 980 981 const uint32_t num_scs = sc_list.GetSize(); 982 if (num_scs > 0) { 983 SymbolContext sc; 984 for (uint32_t sc_idx = 0; sc_idx < num_scs; ++sc_idx) { 985 if (sc_list.GetContextAtIndex(sc_idx, sc)) { 986 if (sc.comp_unit) { 987 const bool can_create = true; 988 VariableListSP comp_unit_varlist_sp( 989 sc.comp_unit->GetVariableList(can_create)); 990 if (comp_unit_varlist_sp) 991 DumpGlobalVariableList(m_exe_ctx, sc, *comp_unit_varlist_sp, 992 s); 993 } else if (sc.module_sp) { 994 // Get all global variables for this module 995 lldb_private::RegularExpression all_globals_regex( 996 llvm::StringRef( 997 ".")); // Any global with at least one character 998 VariableList variable_list; 999 sc.module_sp->FindGlobalVariables(all_globals_regex, UINT32_MAX, 1000 variable_list); 1001 DumpGlobalVariableList(m_exe_ctx, sc, variable_list, s); 1002 } 1003 } 1004 } 1005 } 1006 } 1007 } 1008 1009 if (m_interpreter.TruncationWarningNecessary()) { 1010 result.GetOutputStream().Printf(m_interpreter.TruncationWarningText(), 1011 m_cmd_name.c_str()); 1012 m_interpreter.TruncationWarningGiven(); 1013 } 1014 1015 return result.Succeeded(); 1016 } 1017 1018 OptionGroupOptions m_option_group; 1019 OptionGroupVariable m_option_variable; 1020 OptionGroupFormat m_option_format; 1021 OptionGroupFileList m_option_compile_units; 1022 OptionGroupFileList m_option_shared_libraries; 1023 OptionGroupValueObjectDisplay m_varobj_options; 1024 }; 1025 1026 #pragma mark CommandObjectTargetModulesSearchPathsAdd 1027 1028 class CommandObjectTargetModulesSearchPathsAdd : public CommandObjectParsed { 1029 public: 1030 CommandObjectTargetModulesSearchPathsAdd(CommandInterpreter &interpreter) 1031 : CommandObjectParsed(interpreter, "target modules search-paths add", 1032 "Add new image search paths substitution pairs to " 1033 "the current target.", 1034 nullptr) { 1035 CommandArgumentEntry arg; 1036 CommandArgumentData old_prefix_arg; 1037 CommandArgumentData new_prefix_arg; 1038 1039 // Define the first variant of this arg pair. 1040 old_prefix_arg.arg_type = eArgTypeOldPathPrefix; 1041 old_prefix_arg.arg_repetition = eArgRepeatPairPlus; 1042 1043 // Define the first variant of this arg pair. 1044 new_prefix_arg.arg_type = eArgTypeNewPathPrefix; 1045 new_prefix_arg.arg_repetition = eArgRepeatPairPlus; 1046 1047 // There are two required arguments that must always occur together, i.e. 1048 // an argument "pair". Because they must always occur together, they are 1049 // treated as two variants of one argument rather than two independent 1050 // arguments. Push them both into the first argument position for 1051 // m_arguments... 1052 1053 arg.push_back(old_prefix_arg); 1054 arg.push_back(new_prefix_arg); 1055 1056 m_arguments.push_back(arg); 1057 } 1058 1059 ~CommandObjectTargetModulesSearchPathsAdd() override = default; 1060 1061 protected: 1062 bool DoExecute(Args &command, CommandReturnObject &result) override { 1063 Target *target = GetDebugger().GetSelectedTarget().get(); 1064 if (target) { 1065 const size_t argc = command.GetArgumentCount(); 1066 if (argc & 1) { 1067 result.AppendError("add requires an even number of arguments\n"); 1068 result.SetStatus(eReturnStatusFailed); 1069 } else { 1070 for (size_t i = 0; i < argc; i += 2) { 1071 const char *from = command.GetArgumentAtIndex(i); 1072 const char *to = command.GetArgumentAtIndex(i + 1); 1073 1074 if (from[0] && to[0]) { 1075 Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST); 1076 if (log) { 1077 LLDB_LOGF(log, 1078 "target modules search path adding ImageSearchPath " 1079 "pair: '%s' -> '%s'", 1080 from, to); 1081 } 1082 bool last_pair = ((argc - i) == 2); 1083 target->GetImageSearchPathList().Append( 1084 ConstString(from), ConstString(to), 1085 last_pair); // Notify if this is the last pair 1086 result.SetStatus(eReturnStatusSuccessFinishNoResult); 1087 } else { 1088 if (from[0]) 1089 result.AppendError("<path-prefix> can't be empty\n"); 1090 else 1091 result.AppendError("<new-path-prefix> can't be empty\n"); 1092 result.SetStatus(eReturnStatusFailed); 1093 } 1094 } 1095 } 1096 } else { 1097 result.AppendError("invalid target\n"); 1098 result.SetStatus(eReturnStatusFailed); 1099 } 1100 return result.Succeeded(); 1101 } 1102 }; 1103 1104 #pragma mark CommandObjectTargetModulesSearchPathsClear 1105 1106 class CommandObjectTargetModulesSearchPathsClear : public CommandObjectParsed { 1107 public: 1108 CommandObjectTargetModulesSearchPathsClear(CommandInterpreter &interpreter) 1109 : CommandObjectParsed(interpreter, "target modules search-paths clear", 1110 "Clear all current image search path substitution " 1111 "pairs from the current target.", 1112 "target modules search-paths clear") {} 1113 1114 ~CommandObjectTargetModulesSearchPathsClear() override = default; 1115 1116 protected: 1117 bool DoExecute(Args &command, CommandReturnObject &result) override { 1118 Target *target = GetDebugger().GetSelectedTarget().get(); 1119 if (target) { 1120 bool notify = true; 1121 target->GetImageSearchPathList().Clear(notify); 1122 result.SetStatus(eReturnStatusSuccessFinishNoResult); 1123 } else { 1124 result.AppendError("invalid target\n"); 1125 result.SetStatus(eReturnStatusFailed); 1126 } 1127 return result.Succeeded(); 1128 } 1129 }; 1130 1131 #pragma mark CommandObjectTargetModulesSearchPathsInsert 1132 1133 class CommandObjectTargetModulesSearchPathsInsert : public CommandObjectParsed { 1134 public: 1135 CommandObjectTargetModulesSearchPathsInsert(CommandInterpreter &interpreter) 1136 : CommandObjectParsed(interpreter, "target modules search-paths insert", 1137 "Insert a new image search path substitution pair " 1138 "into the current target at the specified index.", 1139 nullptr) { 1140 CommandArgumentEntry arg1; 1141 CommandArgumentEntry arg2; 1142 CommandArgumentData index_arg; 1143 CommandArgumentData old_prefix_arg; 1144 CommandArgumentData new_prefix_arg; 1145 1146 // Define the first and only variant of this arg. 1147 index_arg.arg_type = eArgTypeIndex; 1148 index_arg.arg_repetition = eArgRepeatPlain; 1149 1150 // Put the one and only variant into the first arg for m_arguments: 1151 arg1.push_back(index_arg); 1152 1153 // Define the first variant of this arg pair. 1154 old_prefix_arg.arg_type = eArgTypeOldPathPrefix; 1155 old_prefix_arg.arg_repetition = eArgRepeatPairPlus; 1156 1157 // Define the first variant of this arg pair. 1158 new_prefix_arg.arg_type = eArgTypeNewPathPrefix; 1159 new_prefix_arg.arg_repetition = eArgRepeatPairPlus; 1160 1161 // There are two required arguments that must always occur together, i.e. 1162 // an argument "pair". Because they must always occur together, they are 1163 // treated as two variants of one argument rather than two independent 1164 // arguments. Push them both into the same argument position for 1165 // m_arguments... 1166 1167 arg2.push_back(old_prefix_arg); 1168 arg2.push_back(new_prefix_arg); 1169 1170 // Add arguments to m_arguments. 1171 m_arguments.push_back(arg1); 1172 m_arguments.push_back(arg2); 1173 } 1174 1175 ~CommandObjectTargetModulesSearchPathsInsert() override = default; 1176 1177 protected: 1178 bool DoExecute(Args &command, CommandReturnObject &result) override { 1179 Target *target = GetDebugger().GetSelectedTarget().get(); 1180 if (target) { 1181 size_t argc = command.GetArgumentCount(); 1182 // check for at least 3 arguments and an odd number of parameters 1183 if (argc >= 3 && argc & 1) { 1184 bool success = false; 1185 1186 uint32_t insert_idx = StringConvert::ToUInt32( 1187 command.GetArgumentAtIndex(0), UINT32_MAX, 0, &success); 1188 1189 if (!success) { 1190 result.AppendErrorWithFormat( 1191 "<index> parameter is not an integer: '%s'.\n", 1192 command.GetArgumentAtIndex(0)); 1193 result.SetStatus(eReturnStatusFailed); 1194 return result.Succeeded(); 1195 } 1196 1197 // shift off the index 1198 command.Shift(); 1199 argc = command.GetArgumentCount(); 1200 1201 for (uint32_t i = 0; i < argc; i += 2, ++insert_idx) { 1202 const char *from = command.GetArgumentAtIndex(i); 1203 const char *to = command.GetArgumentAtIndex(i + 1); 1204 1205 if (from[0] && to[0]) { 1206 bool last_pair = ((argc - i) == 2); 1207 target->GetImageSearchPathList().Insert( 1208 ConstString(from), ConstString(to), insert_idx, last_pair); 1209 result.SetStatus(eReturnStatusSuccessFinishNoResult); 1210 } else { 1211 if (from[0]) 1212 result.AppendError("<path-prefix> can't be empty\n"); 1213 else 1214 result.AppendError("<new-path-prefix> can't be empty\n"); 1215 result.SetStatus(eReturnStatusFailed); 1216 return false; 1217 } 1218 } 1219 } else { 1220 result.AppendError("insert requires at least three arguments\n"); 1221 result.SetStatus(eReturnStatusFailed); 1222 return result.Succeeded(); 1223 } 1224 1225 } else { 1226 result.AppendError("invalid target\n"); 1227 result.SetStatus(eReturnStatusFailed); 1228 } 1229 return result.Succeeded(); 1230 } 1231 }; 1232 1233 #pragma mark CommandObjectTargetModulesSearchPathsList 1234 1235 class CommandObjectTargetModulesSearchPathsList : public CommandObjectParsed { 1236 public: 1237 CommandObjectTargetModulesSearchPathsList(CommandInterpreter &interpreter) 1238 : CommandObjectParsed(interpreter, "target modules search-paths list", 1239 "List all current image search path substitution " 1240 "pairs in the current target.", 1241 "target modules search-paths list") {} 1242 1243 ~CommandObjectTargetModulesSearchPathsList() override = default; 1244 1245 protected: 1246 bool DoExecute(Args &command, CommandReturnObject &result) override { 1247 Target *target = GetDebugger().GetSelectedTarget().get(); 1248 if (target) { 1249 if (command.GetArgumentCount() != 0) { 1250 result.AppendError("list takes no arguments\n"); 1251 result.SetStatus(eReturnStatusFailed); 1252 return result.Succeeded(); 1253 } 1254 1255 target->GetImageSearchPathList().Dump(&result.GetOutputStream()); 1256 result.SetStatus(eReturnStatusSuccessFinishResult); 1257 } else { 1258 result.AppendError("invalid target\n"); 1259 result.SetStatus(eReturnStatusFailed); 1260 } 1261 return result.Succeeded(); 1262 } 1263 }; 1264 1265 #pragma mark CommandObjectTargetModulesSearchPathsQuery 1266 1267 class CommandObjectTargetModulesSearchPathsQuery : public CommandObjectParsed { 1268 public: 1269 CommandObjectTargetModulesSearchPathsQuery(CommandInterpreter &interpreter) 1270 : CommandObjectParsed( 1271 interpreter, "target modules search-paths query", 1272 "Transform a path using the first applicable image search path.", 1273 nullptr) { 1274 CommandArgumentEntry arg; 1275 CommandArgumentData path_arg; 1276 1277 // Define the first (and only) variant of this arg. 1278 path_arg.arg_type = eArgTypeDirectoryName; 1279 path_arg.arg_repetition = eArgRepeatPlain; 1280 1281 // There is only one variant this argument could be; put it into the 1282 // argument entry. 1283 arg.push_back(path_arg); 1284 1285 // Push the data for the first argument into the m_arguments vector. 1286 m_arguments.push_back(arg); 1287 } 1288 1289 ~CommandObjectTargetModulesSearchPathsQuery() override = default; 1290 1291 protected: 1292 bool DoExecute(Args &command, CommandReturnObject &result) override { 1293 Target *target = GetDebugger().GetSelectedTarget().get(); 1294 if (target) { 1295 if (command.GetArgumentCount() != 1) { 1296 result.AppendError("query requires one argument\n"); 1297 result.SetStatus(eReturnStatusFailed); 1298 return result.Succeeded(); 1299 } 1300 1301 ConstString orig(command.GetArgumentAtIndex(0)); 1302 ConstString transformed; 1303 if (target->GetImageSearchPathList().RemapPath(orig, transformed)) 1304 result.GetOutputStream().Printf("%s\n", transformed.GetCString()); 1305 else 1306 result.GetOutputStream().Printf("%s\n", orig.GetCString()); 1307 1308 result.SetStatus(eReturnStatusSuccessFinishResult); 1309 } else { 1310 result.AppendError("invalid target\n"); 1311 result.SetStatus(eReturnStatusFailed); 1312 } 1313 return result.Succeeded(); 1314 } 1315 }; 1316 1317 // Static Helper functions 1318 static void DumpModuleArchitecture(Stream &strm, Module *module, 1319 bool full_triple, uint32_t width) { 1320 if (module) { 1321 StreamString arch_strm; 1322 1323 if (full_triple) 1324 module->GetArchitecture().DumpTriple(arch_strm); 1325 else 1326 arch_strm.PutCString(module->GetArchitecture().GetArchitectureName()); 1327 std::string arch_str = arch_strm.GetString(); 1328 1329 if (width) 1330 strm.Printf("%-*s", width, arch_str.c_str()); 1331 else 1332 strm.PutCString(arch_str); 1333 } 1334 } 1335 1336 static void DumpModuleUUID(Stream &strm, Module *module) { 1337 if (module && module->GetUUID().IsValid()) 1338 module->GetUUID().Dump(&strm); 1339 else 1340 strm.PutCString(" "); 1341 } 1342 1343 static uint32_t DumpCompileUnitLineTable(CommandInterpreter &interpreter, 1344 Stream &strm, Module *module, 1345 const FileSpec &file_spec, 1346 lldb::DescriptionLevel desc_level) { 1347 uint32_t num_matches = 0; 1348 if (module) { 1349 SymbolContextList sc_list; 1350 num_matches = module->ResolveSymbolContextsForFileSpec( 1351 file_spec, 0, false, eSymbolContextCompUnit, sc_list); 1352 1353 for (uint32_t i = 0; i < num_matches; ++i) { 1354 SymbolContext sc; 1355 if (sc_list.GetContextAtIndex(i, sc)) { 1356 if (i > 0) 1357 strm << "\n\n"; 1358 1359 strm << "Line table for " << *static_cast<FileSpec *>(sc.comp_unit) 1360 << " in `" << module->GetFileSpec().GetFilename() << "\n"; 1361 LineTable *line_table = sc.comp_unit->GetLineTable(); 1362 if (line_table) 1363 line_table->GetDescription( 1364 &strm, interpreter.GetExecutionContext().GetTargetPtr(), 1365 desc_level); 1366 else 1367 strm << "No line table"; 1368 } 1369 } 1370 } 1371 return num_matches; 1372 } 1373 1374 static void DumpFullpath(Stream &strm, const FileSpec *file_spec_ptr, 1375 uint32_t width) { 1376 if (file_spec_ptr) { 1377 if (width > 0) { 1378 std::string fullpath = file_spec_ptr->GetPath(); 1379 strm.Printf("%-*s", width, fullpath.c_str()); 1380 return; 1381 } else { 1382 file_spec_ptr->Dump(&strm); 1383 return; 1384 } 1385 } 1386 // Keep the width spacing correct if things go wrong... 1387 if (width > 0) 1388 strm.Printf("%-*s", width, ""); 1389 } 1390 1391 static void DumpDirectory(Stream &strm, const FileSpec *file_spec_ptr, 1392 uint32_t width) { 1393 if (file_spec_ptr) { 1394 if (width > 0) 1395 strm.Printf("%-*s", width, file_spec_ptr->GetDirectory().AsCString("")); 1396 else 1397 file_spec_ptr->GetDirectory().Dump(&strm); 1398 return; 1399 } 1400 // Keep the width spacing correct if things go wrong... 1401 if (width > 0) 1402 strm.Printf("%-*s", width, ""); 1403 } 1404 1405 static void DumpBasename(Stream &strm, const FileSpec *file_spec_ptr, 1406 uint32_t width) { 1407 if (file_spec_ptr) { 1408 if (width > 0) 1409 strm.Printf("%-*s", width, file_spec_ptr->GetFilename().AsCString("")); 1410 else 1411 file_spec_ptr->GetFilename().Dump(&strm); 1412 return; 1413 } 1414 // Keep the width spacing correct if things go wrong... 1415 if (width > 0) 1416 strm.Printf("%-*s", width, ""); 1417 } 1418 1419 static size_t DumpModuleObjfileHeaders(Stream &strm, ModuleList &module_list) { 1420 size_t num_dumped = 0; 1421 std::lock_guard<std::recursive_mutex> guard(module_list.GetMutex()); 1422 const size_t num_modules = module_list.GetSize(); 1423 if (num_modules > 0) { 1424 strm.Printf("Dumping headers for %" PRIu64 " module(s).\n", 1425 static_cast<uint64_t>(num_modules)); 1426 strm.IndentMore(); 1427 for (size_t image_idx = 0; image_idx < num_modules; ++image_idx) { 1428 Module *module = module_list.GetModulePointerAtIndexUnlocked(image_idx); 1429 if (module) { 1430 if (num_dumped++ > 0) { 1431 strm.EOL(); 1432 strm.EOL(); 1433 } 1434 ObjectFile *objfile = module->GetObjectFile(); 1435 if (objfile) 1436 objfile->Dump(&strm); 1437 else { 1438 strm.Format("No object file for module: {0:F}\n", 1439 module->GetFileSpec()); 1440 } 1441 } 1442 } 1443 strm.IndentLess(); 1444 } 1445 return num_dumped; 1446 } 1447 1448 static void DumpModuleSymtab(CommandInterpreter &interpreter, Stream &strm, 1449 Module *module, SortOrder sort_order) { 1450 if (module) { 1451 SymbolVendor *sym_vendor = module->GetSymbolVendor(); 1452 if (sym_vendor) { 1453 Symtab *symtab = sym_vendor->GetSymtab(); 1454 if (symtab) 1455 symtab->Dump(&strm, interpreter.GetExecutionContext().GetTargetPtr(), 1456 sort_order); 1457 } 1458 } 1459 } 1460 1461 static void DumpModuleSections(CommandInterpreter &interpreter, Stream &strm, 1462 Module *module) { 1463 if (module) { 1464 SectionList *section_list = module->GetSectionList(); 1465 if (section_list) { 1466 strm.Printf("Sections for '%s' (%s):\n", 1467 module->GetSpecificationDescription().c_str(), 1468 module->GetArchitecture().GetArchitectureName()); 1469 strm.IndentMore(); 1470 section_list->Dump(&strm, 1471 interpreter.GetExecutionContext().GetTargetPtr(), true, 1472 UINT32_MAX); 1473 strm.IndentLess(); 1474 } 1475 } 1476 } 1477 1478 static bool DumpModuleSymbolVendor(Stream &strm, Module *module) { 1479 if (module) { 1480 SymbolVendor *symbol_vendor = module->GetSymbolVendor(true); 1481 if (symbol_vendor) { 1482 symbol_vendor->Dump(&strm); 1483 return true; 1484 } 1485 } 1486 return false; 1487 } 1488 1489 static void DumpAddress(ExecutionContextScope *exe_scope, 1490 const Address &so_addr, bool verbose, Stream &strm) { 1491 strm.IndentMore(); 1492 strm.Indent(" Address: "); 1493 so_addr.Dump(&strm, exe_scope, Address::DumpStyleModuleWithFileAddress); 1494 strm.PutCString(" ("); 1495 so_addr.Dump(&strm, exe_scope, Address::DumpStyleSectionNameOffset); 1496 strm.PutCString(")\n"); 1497 strm.Indent(" Summary: "); 1498 const uint32_t save_indent = strm.GetIndentLevel(); 1499 strm.SetIndentLevel(save_indent + 13); 1500 so_addr.Dump(&strm, exe_scope, Address::DumpStyleResolvedDescription); 1501 strm.SetIndentLevel(save_indent); 1502 // Print out detailed address information when verbose is enabled 1503 if (verbose) { 1504 strm.EOL(); 1505 so_addr.Dump(&strm, exe_scope, Address::DumpStyleDetailedSymbolContext); 1506 } 1507 strm.IndentLess(); 1508 } 1509 1510 static bool LookupAddressInModule(CommandInterpreter &interpreter, Stream &strm, 1511 Module *module, uint32_t resolve_mask, 1512 lldb::addr_t raw_addr, lldb::addr_t offset, 1513 bool verbose) { 1514 if (module) { 1515 lldb::addr_t addr = raw_addr - offset; 1516 Address so_addr; 1517 SymbolContext sc; 1518 Target *target = interpreter.GetExecutionContext().GetTargetPtr(); 1519 if (target && !target->GetSectionLoadList().IsEmpty()) { 1520 if (!target->GetSectionLoadList().ResolveLoadAddress(addr, so_addr)) 1521 return false; 1522 else if (so_addr.GetModule().get() != module) 1523 return false; 1524 } else { 1525 if (!module->ResolveFileAddress(addr, so_addr)) 1526 return false; 1527 } 1528 1529 ExecutionContextScope *exe_scope = 1530 interpreter.GetExecutionContext().GetBestExecutionContextScope(); 1531 DumpAddress(exe_scope, so_addr, verbose, strm); 1532 // strm.IndentMore(); 1533 // strm.Indent (" Address: "); 1534 // so_addr.Dump (&strm, exe_scope, 1535 // Address::DumpStyleModuleWithFileAddress); 1536 // strm.PutCString (" ("); 1537 // so_addr.Dump (&strm, exe_scope, 1538 // Address::DumpStyleSectionNameOffset); 1539 // strm.PutCString (")\n"); 1540 // strm.Indent (" Summary: "); 1541 // const uint32_t save_indent = strm.GetIndentLevel (); 1542 // strm.SetIndentLevel (save_indent + 13); 1543 // so_addr.Dump (&strm, exe_scope, 1544 // Address::DumpStyleResolvedDescription); 1545 // strm.SetIndentLevel (save_indent); 1546 // // Print out detailed address information when verbose is enabled 1547 // if (verbose) 1548 // { 1549 // strm.EOL(); 1550 // so_addr.Dump (&strm, exe_scope, 1551 // Address::DumpStyleDetailedSymbolContext); 1552 // } 1553 // strm.IndentLess(); 1554 return true; 1555 } 1556 1557 return false; 1558 } 1559 1560 static uint32_t LookupSymbolInModule(CommandInterpreter &interpreter, 1561 Stream &strm, Module *module, 1562 const char *name, bool name_is_regex, 1563 bool verbose) { 1564 if (module) { 1565 SymbolContext sc; 1566 1567 SymbolVendor *sym_vendor = module->GetSymbolVendor(); 1568 if (sym_vendor) { 1569 Symtab *symtab = sym_vendor->GetSymtab(); 1570 if (symtab) { 1571 std::vector<uint32_t> match_indexes; 1572 ConstString symbol_name(name); 1573 uint32_t num_matches = 0; 1574 if (name_is_regex) { 1575 RegularExpression name_regexp(symbol_name.GetStringRef()); 1576 num_matches = symtab->AppendSymbolIndexesMatchingRegExAndType( 1577 name_regexp, eSymbolTypeAny, match_indexes); 1578 } else { 1579 num_matches = 1580 symtab->AppendSymbolIndexesWithName(symbol_name, match_indexes); 1581 } 1582 1583 if (num_matches > 0) { 1584 strm.Indent(); 1585 strm.Printf("%u symbols match %s'%s' in ", num_matches, 1586 name_is_regex ? "the regular expression " : "", name); 1587 DumpFullpath(strm, &module->GetFileSpec(), 0); 1588 strm.PutCString(":\n"); 1589 strm.IndentMore(); 1590 for (uint32_t i = 0; i < num_matches; ++i) { 1591 Symbol *symbol = symtab->SymbolAtIndex(match_indexes[i]); 1592 if (symbol && symbol->ValueIsAddress()) { 1593 DumpAddress(interpreter.GetExecutionContext() 1594 .GetBestExecutionContextScope(), 1595 symbol->GetAddressRef(), verbose, strm); 1596 } 1597 } 1598 strm.IndentLess(); 1599 return num_matches; 1600 } 1601 } 1602 } 1603 } 1604 return 0; 1605 } 1606 1607 static void DumpSymbolContextList(ExecutionContextScope *exe_scope, 1608 Stream &strm, SymbolContextList &sc_list, 1609 bool verbose) { 1610 strm.IndentMore(); 1611 1612 const uint32_t num_matches = sc_list.GetSize(); 1613 1614 for (uint32_t i = 0; i < num_matches; ++i) { 1615 SymbolContext sc; 1616 if (sc_list.GetContextAtIndex(i, sc)) { 1617 AddressRange range; 1618 1619 sc.GetAddressRange(eSymbolContextEverything, 0, true, range); 1620 1621 DumpAddress(exe_scope, range.GetBaseAddress(), verbose, strm); 1622 } 1623 } 1624 strm.IndentLess(); 1625 } 1626 1627 static size_t LookupFunctionInModule(CommandInterpreter &interpreter, 1628 Stream &strm, Module *module, 1629 const char *name, bool name_is_regex, 1630 bool include_inlines, bool include_symbols, 1631 bool verbose) { 1632 if (module && name && name[0]) { 1633 SymbolContextList sc_list; 1634 const bool append = true; 1635 size_t num_matches = 0; 1636 if (name_is_regex) { 1637 RegularExpression function_name_regex((llvm::StringRef(name))); 1638 num_matches = module->FindFunctions(function_name_regex, include_symbols, 1639 include_inlines, append, sc_list); 1640 } else { 1641 ConstString function_name(name); 1642 num_matches = module->FindFunctions( 1643 function_name, nullptr, eFunctionNameTypeAuto, include_symbols, 1644 include_inlines, append, sc_list); 1645 } 1646 1647 if (num_matches) { 1648 strm.Indent(); 1649 strm.Printf("%" PRIu64 " match%s found in ", (uint64_t)num_matches, 1650 num_matches > 1 ? "es" : ""); 1651 DumpFullpath(strm, &module->GetFileSpec(), 0); 1652 strm.PutCString(":\n"); 1653 DumpSymbolContextList( 1654 interpreter.GetExecutionContext().GetBestExecutionContextScope(), 1655 strm, sc_list, verbose); 1656 } 1657 return num_matches; 1658 } 1659 return 0; 1660 } 1661 1662 static size_t LookupTypeInModule(CommandInterpreter &interpreter, Stream &strm, 1663 Module *module, const char *name_cstr, 1664 bool name_is_regex) { 1665 if (module && name_cstr && name_cstr[0]) { 1666 TypeList type_list; 1667 const uint32_t max_num_matches = UINT32_MAX; 1668 size_t num_matches = 0; 1669 bool name_is_fully_qualified = false; 1670 1671 ConstString name(name_cstr); 1672 llvm::DenseSet<lldb_private::SymbolFile *> searched_symbol_files; 1673 num_matches = 1674 module->FindTypes(name, name_is_fully_qualified, max_num_matches, 1675 searched_symbol_files, type_list); 1676 1677 if (num_matches) { 1678 strm.Indent(); 1679 strm.Printf("%" PRIu64 " match%s found in ", (uint64_t)num_matches, 1680 num_matches > 1 ? "es" : ""); 1681 DumpFullpath(strm, &module->GetFileSpec(), 0); 1682 strm.PutCString(":\n"); 1683 for (TypeSP type_sp : type_list.Types()) { 1684 if (type_sp) { 1685 // Resolve the clang type so that any forward references to types 1686 // that haven't yet been parsed will get parsed. 1687 type_sp->GetFullCompilerType(); 1688 type_sp->GetDescription(&strm, eDescriptionLevelFull, true); 1689 // Print all typedef chains 1690 TypeSP typedef_type_sp(type_sp); 1691 TypeSP typedefed_type_sp(typedef_type_sp->GetTypedefType()); 1692 while (typedefed_type_sp) { 1693 strm.EOL(); 1694 strm.Printf(" typedef '%s': ", 1695 typedef_type_sp->GetName().GetCString()); 1696 typedefed_type_sp->GetFullCompilerType(); 1697 typedefed_type_sp->GetDescription(&strm, eDescriptionLevelFull, 1698 true); 1699 typedef_type_sp = typedefed_type_sp; 1700 typedefed_type_sp = typedef_type_sp->GetTypedefType(); 1701 } 1702 } 1703 strm.EOL(); 1704 } 1705 } 1706 return num_matches; 1707 } 1708 return 0; 1709 } 1710 1711 static size_t LookupTypeHere(CommandInterpreter &interpreter, Stream &strm, 1712 Module &module, const char *name_cstr, 1713 bool name_is_regex) { 1714 TypeList type_list; 1715 const uint32_t max_num_matches = UINT32_MAX; 1716 size_t num_matches = 1; 1717 bool name_is_fully_qualified = false; 1718 1719 ConstString name(name_cstr); 1720 llvm::DenseSet<SymbolFile *> searched_symbol_files; 1721 num_matches = module.FindTypes(name, name_is_fully_qualified, max_num_matches, 1722 searched_symbol_files, type_list); 1723 1724 if (num_matches) { 1725 strm.Indent(); 1726 strm.PutCString("Best match found in "); 1727 DumpFullpath(strm, &module.GetFileSpec(), 0); 1728 strm.PutCString(":\n"); 1729 1730 TypeSP type_sp(type_list.GetTypeAtIndex(0)); 1731 if (type_sp) { 1732 // Resolve the clang type so that any forward references to types that 1733 // haven't yet been parsed will get parsed. 1734 type_sp->GetFullCompilerType(); 1735 type_sp->GetDescription(&strm, eDescriptionLevelFull, true); 1736 // Print all typedef chains 1737 TypeSP typedef_type_sp(type_sp); 1738 TypeSP typedefed_type_sp(typedef_type_sp->GetTypedefType()); 1739 while (typedefed_type_sp) { 1740 strm.EOL(); 1741 strm.Printf(" typedef '%s': ", 1742 typedef_type_sp->GetName().GetCString()); 1743 typedefed_type_sp->GetFullCompilerType(); 1744 typedefed_type_sp->GetDescription(&strm, eDescriptionLevelFull, true); 1745 typedef_type_sp = typedefed_type_sp; 1746 typedefed_type_sp = typedef_type_sp->GetTypedefType(); 1747 } 1748 } 1749 strm.EOL(); 1750 } 1751 return num_matches; 1752 } 1753 1754 static uint32_t LookupFileAndLineInModule(CommandInterpreter &interpreter, 1755 Stream &strm, Module *module, 1756 const FileSpec &file_spec, 1757 uint32_t line, bool check_inlines, 1758 bool verbose) { 1759 if (module && file_spec) { 1760 SymbolContextList sc_list; 1761 const uint32_t num_matches = module->ResolveSymbolContextsForFileSpec( 1762 file_spec, line, check_inlines, eSymbolContextEverything, sc_list); 1763 if (num_matches > 0) { 1764 strm.Indent(); 1765 strm.Printf("%u match%s found in ", num_matches, 1766 num_matches > 1 ? "es" : ""); 1767 strm << file_spec; 1768 if (line > 0) 1769 strm.Printf(":%u", line); 1770 strm << " in "; 1771 DumpFullpath(strm, &module->GetFileSpec(), 0); 1772 strm.PutCString(":\n"); 1773 DumpSymbolContextList( 1774 interpreter.GetExecutionContext().GetBestExecutionContextScope(), 1775 strm, sc_list, verbose); 1776 return num_matches; 1777 } 1778 } 1779 return 0; 1780 } 1781 1782 static size_t FindModulesByName(Target *target, const char *module_name, 1783 ModuleList &module_list, 1784 bool check_global_list) { 1785 FileSpec module_file_spec(module_name); 1786 ModuleSpec module_spec(module_file_spec); 1787 1788 const size_t initial_size = module_list.GetSize(); 1789 1790 if (check_global_list) { 1791 // Check the global list 1792 std::lock_guard<std::recursive_mutex> guard( 1793 Module::GetAllocationModuleCollectionMutex()); 1794 const size_t num_modules = Module::GetNumberAllocatedModules(); 1795 ModuleSP module_sp; 1796 for (size_t image_idx = 0; image_idx < num_modules; ++image_idx) { 1797 Module *module = Module::GetAllocatedModuleAtIndex(image_idx); 1798 1799 if (module) { 1800 if (module->MatchesModuleSpec(module_spec)) { 1801 module_sp = module->shared_from_this(); 1802 module_list.AppendIfNeeded(module_sp); 1803 } 1804 } 1805 } 1806 } else { 1807 if (target) { 1808 const size_t num_matches = 1809 target->GetImages().FindModules(module_spec, module_list); 1810 1811 // Not found in our module list for our target, check the main shared 1812 // module list in case it is a extra file used somewhere else 1813 if (num_matches == 0) { 1814 module_spec.GetArchitecture() = target->GetArchitecture(); 1815 ModuleList::FindSharedModules(module_spec, module_list); 1816 } 1817 } else { 1818 ModuleList::FindSharedModules(module_spec, module_list); 1819 } 1820 } 1821 1822 return module_list.GetSize() - initial_size; 1823 } 1824 1825 #pragma mark CommandObjectTargetModulesModuleAutoComplete 1826 1827 // A base command object class that can auto complete with module file 1828 // paths 1829 1830 class CommandObjectTargetModulesModuleAutoComplete 1831 : public CommandObjectParsed { 1832 public: 1833 CommandObjectTargetModulesModuleAutoComplete(CommandInterpreter &interpreter, 1834 const char *name, 1835 const char *help, 1836 const char *syntax) 1837 : CommandObjectParsed(interpreter, name, help, syntax) { 1838 CommandArgumentEntry arg; 1839 CommandArgumentData file_arg; 1840 1841 // Define the first (and only) variant of this arg. 1842 file_arg.arg_type = eArgTypeFilename; 1843 file_arg.arg_repetition = eArgRepeatStar; 1844 1845 // There is only one variant this argument could be; put it into the 1846 // argument entry. 1847 arg.push_back(file_arg); 1848 1849 // Push the data for the first argument into the m_arguments vector. 1850 m_arguments.push_back(arg); 1851 } 1852 1853 ~CommandObjectTargetModulesModuleAutoComplete() override = default; 1854 1855 int HandleArgumentCompletion( 1856 CompletionRequest &request, 1857 OptionElementVector &opt_element_vector) override { 1858 CommandCompletions::InvokeCommonCompletionCallbacks( 1859 GetCommandInterpreter(), CommandCompletions::eModuleCompletion, request, 1860 nullptr); 1861 return request.GetNumberOfMatches(); 1862 } 1863 }; 1864 1865 #pragma mark CommandObjectTargetModulesSourceFileAutoComplete 1866 1867 // A base command object class that can auto complete with module source 1868 // file paths 1869 1870 class CommandObjectTargetModulesSourceFileAutoComplete 1871 : public CommandObjectParsed { 1872 public: 1873 CommandObjectTargetModulesSourceFileAutoComplete( 1874 CommandInterpreter &interpreter, const char *name, const char *help, 1875 const char *syntax, uint32_t flags) 1876 : CommandObjectParsed(interpreter, name, help, syntax, flags) { 1877 CommandArgumentEntry arg; 1878 CommandArgumentData source_file_arg; 1879 1880 // Define the first (and only) variant of this arg. 1881 source_file_arg.arg_type = eArgTypeSourceFile; 1882 source_file_arg.arg_repetition = eArgRepeatPlus; 1883 1884 // There is only one variant this argument could be; put it into the 1885 // argument entry. 1886 arg.push_back(source_file_arg); 1887 1888 // Push the data for the first argument into the m_arguments vector. 1889 m_arguments.push_back(arg); 1890 } 1891 1892 ~CommandObjectTargetModulesSourceFileAutoComplete() override = default; 1893 1894 int HandleArgumentCompletion( 1895 CompletionRequest &request, 1896 OptionElementVector &opt_element_vector) override { 1897 CommandCompletions::InvokeCommonCompletionCallbacks( 1898 GetCommandInterpreter(), CommandCompletions::eSourceFileCompletion, 1899 request, nullptr); 1900 return request.GetNumberOfMatches(); 1901 } 1902 }; 1903 1904 #pragma mark CommandObjectTargetModulesDumpObjfile 1905 1906 class CommandObjectTargetModulesDumpObjfile 1907 : public CommandObjectTargetModulesModuleAutoComplete { 1908 public: 1909 CommandObjectTargetModulesDumpObjfile(CommandInterpreter &interpreter) 1910 : CommandObjectTargetModulesModuleAutoComplete( 1911 interpreter, "target modules dump objfile", 1912 "Dump the object file headers from one or more target modules.", 1913 nullptr) {} 1914 1915 ~CommandObjectTargetModulesDumpObjfile() override = default; 1916 1917 protected: 1918 bool DoExecute(Args &command, CommandReturnObject &result) override { 1919 Target *target = GetDebugger().GetSelectedTarget().get(); 1920 if (target == nullptr) { 1921 result.AppendError("invalid target, create a debug target using the " 1922 "'target create' command"); 1923 result.SetStatus(eReturnStatusFailed); 1924 return false; 1925 } 1926 1927 uint32_t addr_byte_size = target->GetArchitecture().GetAddressByteSize(); 1928 result.GetOutputStream().SetAddressByteSize(addr_byte_size); 1929 result.GetErrorStream().SetAddressByteSize(addr_byte_size); 1930 1931 size_t num_dumped = 0; 1932 if (command.GetArgumentCount() == 0) { 1933 // Dump all headers for all modules images 1934 num_dumped = DumpModuleObjfileHeaders(result.GetOutputStream(), 1935 target->GetImages()); 1936 if (num_dumped == 0) { 1937 result.AppendError("the target has no associated executable images"); 1938 result.SetStatus(eReturnStatusFailed); 1939 } 1940 } else { 1941 // Find the modules that match the basename or full path. 1942 ModuleList module_list; 1943 const char *arg_cstr; 1944 for (int arg_idx = 0; 1945 (arg_cstr = command.GetArgumentAtIndex(arg_idx)) != nullptr; 1946 ++arg_idx) { 1947 size_t num_matched = 1948 FindModulesByName(target, arg_cstr, module_list, true); 1949 if (num_matched == 0) { 1950 result.AppendWarningWithFormat( 1951 "Unable to find an image that matches '%s'.\n", arg_cstr); 1952 } 1953 } 1954 // Dump all the modules we found. 1955 num_dumped = 1956 DumpModuleObjfileHeaders(result.GetOutputStream(), module_list); 1957 } 1958 1959 if (num_dumped > 0) { 1960 result.SetStatus(eReturnStatusSuccessFinishResult); 1961 } else { 1962 result.AppendError("no matching executable images found"); 1963 result.SetStatus(eReturnStatusFailed); 1964 } 1965 return result.Succeeded(); 1966 } 1967 }; 1968 1969 #pragma mark CommandObjectTargetModulesDumpSymtab 1970 1971 static constexpr OptionEnumValueElement g_sort_option_enumeration[] = { 1972 { 1973 eSortOrderNone, 1974 "none", 1975 "No sorting, use the original symbol table order.", 1976 }, 1977 { 1978 eSortOrderByAddress, 1979 "address", 1980 "Sort output by symbol address.", 1981 }, 1982 { 1983 eSortOrderByName, 1984 "name", 1985 "Sort output by symbol name.", 1986 }, 1987 }; 1988 1989 #define LLDB_OPTIONS_target_modules_dump_symtab 1990 #include "CommandOptions.inc" 1991 1992 class CommandObjectTargetModulesDumpSymtab 1993 : public CommandObjectTargetModulesModuleAutoComplete { 1994 public: 1995 CommandObjectTargetModulesDumpSymtab(CommandInterpreter &interpreter) 1996 : CommandObjectTargetModulesModuleAutoComplete( 1997 interpreter, "target modules dump symtab", 1998 "Dump the symbol table from one or more target modules.", nullptr), 1999 m_options() {} 2000 2001 ~CommandObjectTargetModulesDumpSymtab() override = default; 2002 2003 Options *GetOptions() override { return &m_options; } 2004 2005 class CommandOptions : public Options { 2006 public: 2007 CommandOptions() : Options(), m_sort_order(eSortOrderNone) {} 2008 2009 ~CommandOptions() override = default; 2010 2011 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, 2012 ExecutionContext *execution_context) override { 2013 Status error; 2014 const int short_option = m_getopt_table[option_idx].val; 2015 2016 switch (short_option) { 2017 case 's': 2018 m_sort_order = (SortOrder)OptionArgParser::ToOptionEnum( 2019 option_arg, GetDefinitions()[option_idx].enum_values, 2020 eSortOrderNone, error); 2021 break; 2022 2023 default: 2024 error.SetErrorStringWithFormat("invalid short option character '%c'", 2025 short_option); 2026 break; 2027 } 2028 return error; 2029 } 2030 2031 void OptionParsingStarting(ExecutionContext *execution_context) override { 2032 m_sort_order = eSortOrderNone; 2033 } 2034 2035 llvm::ArrayRef<OptionDefinition> GetDefinitions() override { 2036 return llvm::makeArrayRef(g_target_modules_dump_symtab_options); 2037 } 2038 2039 SortOrder m_sort_order; 2040 }; 2041 2042 protected: 2043 bool DoExecute(Args &command, CommandReturnObject &result) override { 2044 Target *target = GetDebugger().GetSelectedTarget().get(); 2045 if (target == nullptr) { 2046 result.AppendError("invalid target, create a debug target using the " 2047 "'target create' command"); 2048 result.SetStatus(eReturnStatusFailed); 2049 return false; 2050 } else { 2051 uint32_t num_dumped = 0; 2052 2053 uint32_t addr_byte_size = target->GetArchitecture().GetAddressByteSize(); 2054 result.GetOutputStream().SetAddressByteSize(addr_byte_size); 2055 result.GetErrorStream().SetAddressByteSize(addr_byte_size); 2056 2057 if (command.GetArgumentCount() == 0) { 2058 // Dump all sections for all modules images 2059 std::lock_guard<std::recursive_mutex> guard( 2060 target->GetImages().GetMutex()); 2061 const size_t num_modules = target->GetImages().GetSize(); 2062 if (num_modules > 0) { 2063 result.GetOutputStream().Printf("Dumping symbol table for %" PRIu64 2064 " modules.\n", 2065 (uint64_t)num_modules); 2066 for (size_t image_idx = 0; image_idx < num_modules; ++image_idx) { 2067 if (num_dumped > 0) { 2068 result.GetOutputStream().EOL(); 2069 result.GetOutputStream().EOL(); 2070 } 2071 if (m_interpreter.WasInterrupted()) 2072 break; 2073 num_dumped++; 2074 DumpModuleSymtab( 2075 m_interpreter, result.GetOutputStream(), 2076 target->GetImages().GetModulePointerAtIndexUnlocked(image_idx), 2077 m_options.m_sort_order); 2078 } 2079 } else { 2080 result.AppendError("the target has no associated executable images"); 2081 result.SetStatus(eReturnStatusFailed); 2082 return false; 2083 } 2084 } else { 2085 // Dump specified images (by basename or fullpath) 2086 const char *arg_cstr; 2087 for (int arg_idx = 0; 2088 (arg_cstr = command.GetArgumentAtIndex(arg_idx)) != nullptr; 2089 ++arg_idx) { 2090 ModuleList module_list; 2091 const size_t num_matches = 2092 FindModulesByName(target, arg_cstr, module_list, true); 2093 if (num_matches > 0) { 2094 for (size_t i = 0; i < num_matches; ++i) { 2095 Module *module = module_list.GetModulePointerAtIndex(i); 2096 if (module) { 2097 if (num_dumped > 0) { 2098 result.GetOutputStream().EOL(); 2099 result.GetOutputStream().EOL(); 2100 } 2101 if (m_interpreter.WasInterrupted()) 2102 break; 2103 num_dumped++; 2104 DumpModuleSymtab(m_interpreter, result.GetOutputStream(), 2105 module, m_options.m_sort_order); 2106 } 2107 } 2108 } else 2109 result.AppendWarningWithFormat( 2110 "Unable to find an image that matches '%s'.\n", arg_cstr); 2111 } 2112 } 2113 2114 if (num_dumped > 0) 2115 result.SetStatus(eReturnStatusSuccessFinishResult); 2116 else { 2117 result.AppendError("no matching executable images found"); 2118 result.SetStatus(eReturnStatusFailed); 2119 } 2120 } 2121 return result.Succeeded(); 2122 } 2123 2124 CommandOptions m_options; 2125 }; 2126 2127 #pragma mark CommandObjectTargetModulesDumpSections 2128 2129 // Image section dumping command 2130 2131 class CommandObjectTargetModulesDumpSections 2132 : public CommandObjectTargetModulesModuleAutoComplete { 2133 public: 2134 CommandObjectTargetModulesDumpSections(CommandInterpreter &interpreter) 2135 : CommandObjectTargetModulesModuleAutoComplete( 2136 interpreter, "target modules dump sections", 2137 "Dump the sections from one or more target modules.", 2138 //"target modules dump sections [<file1> ...]") 2139 nullptr) {} 2140 2141 ~CommandObjectTargetModulesDumpSections() override = default; 2142 2143 protected: 2144 bool DoExecute(Args &command, CommandReturnObject &result) override { 2145 Target *target = GetDebugger().GetSelectedTarget().get(); 2146 if (target == nullptr) { 2147 result.AppendError("invalid target, create a debug target using the " 2148 "'target create' command"); 2149 result.SetStatus(eReturnStatusFailed); 2150 return false; 2151 } else { 2152 uint32_t num_dumped = 0; 2153 2154 uint32_t addr_byte_size = target->GetArchitecture().GetAddressByteSize(); 2155 result.GetOutputStream().SetAddressByteSize(addr_byte_size); 2156 result.GetErrorStream().SetAddressByteSize(addr_byte_size); 2157 2158 if (command.GetArgumentCount() == 0) { 2159 // Dump all sections for all modules images 2160 const size_t num_modules = target->GetImages().GetSize(); 2161 if (num_modules > 0) { 2162 result.GetOutputStream().Printf("Dumping sections for %" PRIu64 2163 " modules.\n", 2164 (uint64_t)num_modules); 2165 for (size_t image_idx = 0; image_idx < num_modules; ++image_idx) { 2166 if (m_interpreter.WasInterrupted()) 2167 break; 2168 num_dumped++; 2169 DumpModuleSections( 2170 m_interpreter, result.GetOutputStream(), 2171 target->GetImages().GetModulePointerAtIndex(image_idx)); 2172 } 2173 } else { 2174 result.AppendError("the target has no associated executable images"); 2175 result.SetStatus(eReturnStatusFailed); 2176 return false; 2177 } 2178 } else { 2179 // Dump specified images (by basename or fullpath) 2180 const char *arg_cstr; 2181 for (int arg_idx = 0; 2182 (arg_cstr = command.GetArgumentAtIndex(arg_idx)) != nullptr; 2183 ++arg_idx) { 2184 ModuleList module_list; 2185 const size_t num_matches = 2186 FindModulesByName(target, arg_cstr, module_list, true); 2187 if (num_matches > 0) { 2188 for (size_t i = 0; i < num_matches; ++i) { 2189 if (m_interpreter.WasInterrupted()) 2190 break; 2191 Module *module = module_list.GetModulePointerAtIndex(i); 2192 if (module) { 2193 num_dumped++; 2194 DumpModuleSections(m_interpreter, result.GetOutputStream(), 2195 module); 2196 } 2197 } 2198 } else { 2199 // Check the global list 2200 std::lock_guard<std::recursive_mutex> guard( 2201 Module::GetAllocationModuleCollectionMutex()); 2202 2203 result.AppendWarningWithFormat( 2204 "Unable to find an image that matches '%s'.\n", arg_cstr); 2205 } 2206 } 2207 } 2208 2209 if (num_dumped > 0) 2210 result.SetStatus(eReturnStatusSuccessFinishResult); 2211 else { 2212 result.AppendError("no matching executable images found"); 2213 result.SetStatus(eReturnStatusFailed); 2214 } 2215 } 2216 return result.Succeeded(); 2217 } 2218 }; 2219 2220 #pragma mark CommandObjectTargetModulesDumpSections 2221 2222 // Clang AST dumping command 2223 2224 class CommandObjectTargetModulesDumpClangAST 2225 : public CommandObjectTargetModulesModuleAutoComplete { 2226 public: 2227 CommandObjectTargetModulesDumpClangAST(CommandInterpreter &interpreter) 2228 : CommandObjectTargetModulesModuleAutoComplete( 2229 interpreter, "target modules dump ast", 2230 "Dump the clang ast for a given module's symbol file.", 2231 //"target modules dump ast [<file1> ...]") 2232 nullptr) {} 2233 2234 ~CommandObjectTargetModulesDumpClangAST() override = default; 2235 2236 protected: 2237 bool DoExecute(Args &command, CommandReturnObject &result) override { 2238 Target *target = GetDebugger().GetSelectedTarget().get(); 2239 if (target == nullptr) { 2240 result.AppendError("invalid target, create a debug target using the " 2241 "'target create' command"); 2242 result.SetStatus(eReturnStatusFailed); 2243 return false; 2244 } 2245 2246 const size_t num_modules = target->GetImages().GetSize(); 2247 if (num_modules == 0) { 2248 result.AppendError("the target has no associated executable images"); 2249 result.SetStatus(eReturnStatusFailed); 2250 return false; 2251 } 2252 2253 if (command.GetArgumentCount() == 0) { 2254 // Dump all ASTs for all modules images 2255 result.GetOutputStream().Printf("Dumping clang ast for %" PRIu64 2256 " modules.\n", 2257 (uint64_t)num_modules); 2258 for (size_t image_idx = 0; image_idx < num_modules; ++image_idx) { 2259 if (m_interpreter.WasInterrupted()) 2260 break; 2261 Module *m = target->GetImages().GetModulePointerAtIndex(image_idx); 2262 SymbolFile *sf = m->GetSymbolVendor()->GetSymbolFile(); 2263 sf->DumpClangAST(result.GetOutputStream()); 2264 } 2265 result.SetStatus(eReturnStatusSuccessFinishResult); 2266 return true; 2267 } 2268 2269 // Dump specified ASTs (by basename or fullpath) 2270 for (const Args::ArgEntry &arg : command.entries()) { 2271 ModuleList module_list; 2272 const size_t num_matches = 2273 FindModulesByName(target, arg.c_str(), module_list, true); 2274 if (num_matches == 0) { 2275 // Check the global list 2276 std::lock_guard<std::recursive_mutex> guard( 2277 Module::GetAllocationModuleCollectionMutex()); 2278 2279 result.AppendWarningWithFormat( 2280 "Unable to find an image that matches '%s'.\n", arg.c_str()); 2281 continue; 2282 } 2283 2284 for (size_t i = 0; i < num_matches; ++i) { 2285 if (m_interpreter.WasInterrupted()) 2286 break; 2287 Module *m = module_list.GetModulePointerAtIndex(i); 2288 SymbolFile *sf = m->GetSymbolVendor()->GetSymbolFile(); 2289 sf->DumpClangAST(result.GetOutputStream()); 2290 } 2291 } 2292 result.SetStatus(eReturnStatusSuccessFinishResult); 2293 return true; 2294 } 2295 }; 2296 2297 #pragma mark CommandObjectTargetModulesDumpSymfile 2298 2299 // Image debug symbol dumping command 2300 2301 class CommandObjectTargetModulesDumpSymfile 2302 : public CommandObjectTargetModulesModuleAutoComplete { 2303 public: 2304 CommandObjectTargetModulesDumpSymfile(CommandInterpreter &interpreter) 2305 : CommandObjectTargetModulesModuleAutoComplete( 2306 interpreter, "target modules dump symfile", 2307 "Dump the debug symbol file for one or more target modules.", 2308 //"target modules dump symfile [<file1> ...]") 2309 nullptr) {} 2310 2311 ~CommandObjectTargetModulesDumpSymfile() override = default; 2312 2313 protected: 2314 bool DoExecute(Args &command, CommandReturnObject &result) override { 2315 Target *target = GetDebugger().GetSelectedTarget().get(); 2316 if (target == nullptr) { 2317 result.AppendError("invalid target, create a debug target using the " 2318 "'target create' command"); 2319 result.SetStatus(eReturnStatusFailed); 2320 return false; 2321 } else { 2322 uint32_t num_dumped = 0; 2323 2324 uint32_t addr_byte_size = target->GetArchitecture().GetAddressByteSize(); 2325 result.GetOutputStream().SetAddressByteSize(addr_byte_size); 2326 result.GetErrorStream().SetAddressByteSize(addr_byte_size); 2327 2328 if (command.GetArgumentCount() == 0) { 2329 // Dump all sections for all modules images 2330 const ModuleList &target_modules = target->GetImages(); 2331 std::lock_guard<std::recursive_mutex> guard(target_modules.GetMutex()); 2332 const size_t num_modules = target_modules.GetSize(); 2333 if (num_modules > 0) { 2334 result.GetOutputStream().Printf("Dumping debug symbols for %" PRIu64 2335 " modules.\n", 2336 (uint64_t)num_modules); 2337 for (uint32_t image_idx = 0; image_idx < num_modules; ++image_idx) { 2338 if (m_interpreter.WasInterrupted()) 2339 break; 2340 if (DumpModuleSymbolVendor( 2341 result.GetOutputStream(), 2342 target_modules.GetModulePointerAtIndexUnlocked(image_idx))) 2343 num_dumped++; 2344 } 2345 } else { 2346 result.AppendError("the target has no associated executable images"); 2347 result.SetStatus(eReturnStatusFailed); 2348 return false; 2349 } 2350 } else { 2351 // Dump specified images (by basename or fullpath) 2352 const char *arg_cstr; 2353 for (int arg_idx = 0; 2354 (arg_cstr = command.GetArgumentAtIndex(arg_idx)) != nullptr; 2355 ++arg_idx) { 2356 ModuleList module_list; 2357 const size_t num_matches = 2358 FindModulesByName(target, arg_cstr, module_list, true); 2359 if (num_matches > 0) { 2360 for (size_t i = 0; i < num_matches; ++i) { 2361 if (m_interpreter.WasInterrupted()) 2362 break; 2363 Module *module = module_list.GetModulePointerAtIndex(i); 2364 if (module) { 2365 if (DumpModuleSymbolVendor(result.GetOutputStream(), module)) 2366 num_dumped++; 2367 } 2368 } 2369 } else 2370 result.AppendWarningWithFormat( 2371 "Unable to find an image that matches '%s'.\n", arg_cstr); 2372 } 2373 } 2374 2375 if (num_dumped > 0) 2376 result.SetStatus(eReturnStatusSuccessFinishResult); 2377 else { 2378 result.AppendError("no matching executable images found"); 2379 result.SetStatus(eReturnStatusFailed); 2380 } 2381 } 2382 return result.Succeeded(); 2383 } 2384 }; 2385 2386 #pragma mark CommandObjectTargetModulesDumpLineTable 2387 #define LLDB_OPTIONS_target_modules_dump 2388 #include "CommandOptions.inc" 2389 2390 // Image debug line table dumping command 2391 2392 class CommandObjectTargetModulesDumpLineTable 2393 : public CommandObjectTargetModulesSourceFileAutoComplete { 2394 public: 2395 CommandObjectTargetModulesDumpLineTable(CommandInterpreter &interpreter) 2396 : CommandObjectTargetModulesSourceFileAutoComplete( 2397 interpreter, "target modules dump line-table", 2398 "Dump the line table for one or more compilation units.", nullptr, 2399 eCommandRequiresTarget) {} 2400 2401 ~CommandObjectTargetModulesDumpLineTable() override = default; 2402 2403 Options *GetOptions() override { return &m_options; } 2404 2405 protected: 2406 bool DoExecute(Args &command, CommandReturnObject &result) override { 2407 Target *target = m_exe_ctx.GetTargetPtr(); 2408 uint32_t total_num_dumped = 0; 2409 2410 uint32_t addr_byte_size = target->GetArchitecture().GetAddressByteSize(); 2411 result.GetOutputStream().SetAddressByteSize(addr_byte_size); 2412 result.GetErrorStream().SetAddressByteSize(addr_byte_size); 2413 2414 if (command.GetArgumentCount() == 0) { 2415 result.AppendError("file option must be specified."); 2416 result.SetStatus(eReturnStatusFailed); 2417 return result.Succeeded(); 2418 } else { 2419 // Dump specified images (by basename or fullpath) 2420 const char *arg_cstr; 2421 for (int arg_idx = 0; 2422 (arg_cstr = command.GetArgumentAtIndex(arg_idx)) != nullptr; 2423 ++arg_idx) { 2424 FileSpec file_spec(arg_cstr); 2425 2426 const ModuleList &target_modules = target->GetImages(); 2427 std::lock_guard<std::recursive_mutex> guard(target_modules.GetMutex()); 2428 const size_t num_modules = target_modules.GetSize(); 2429 if (num_modules > 0) { 2430 uint32_t num_dumped = 0; 2431 for (uint32_t i = 0; i < num_modules; ++i) { 2432 if (m_interpreter.WasInterrupted()) 2433 break; 2434 if (DumpCompileUnitLineTable( 2435 m_interpreter, result.GetOutputStream(), 2436 target_modules.GetModulePointerAtIndexUnlocked(i), 2437 file_spec, 2438 m_options.m_verbose ? eDescriptionLevelFull 2439 : eDescriptionLevelBrief)) 2440 num_dumped++; 2441 } 2442 if (num_dumped == 0) 2443 result.AppendWarningWithFormat( 2444 "No source filenames matched '%s'.\n", arg_cstr); 2445 else 2446 total_num_dumped += num_dumped; 2447 } 2448 } 2449 } 2450 2451 if (total_num_dumped > 0) 2452 result.SetStatus(eReturnStatusSuccessFinishResult); 2453 else { 2454 result.AppendError("no source filenames matched any command arguments"); 2455 result.SetStatus(eReturnStatusFailed); 2456 } 2457 return result.Succeeded(); 2458 } 2459 2460 class CommandOptions : public Options { 2461 public: 2462 CommandOptions() : Options() { OptionParsingStarting(nullptr); } 2463 2464 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, 2465 ExecutionContext *execution_context) override { 2466 assert(option_idx == 0 && "We only have one option."); 2467 m_verbose = true; 2468 2469 return Status(); 2470 } 2471 2472 void OptionParsingStarting(ExecutionContext *execution_context) override { 2473 m_verbose = false; 2474 } 2475 2476 llvm::ArrayRef<OptionDefinition> GetDefinitions() override { 2477 return llvm::makeArrayRef(g_target_modules_dump_options); 2478 } 2479 2480 bool m_verbose; 2481 }; 2482 2483 CommandOptions m_options; 2484 }; 2485 2486 #pragma mark CommandObjectTargetModulesDump 2487 2488 // Dump multi-word command for target modules 2489 2490 class CommandObjectTargetModulesDump : public CommandObjectMultiword { 2491 public: 2492 // Constructors and Destructors 2493 CommandObjectTargetModulesDump(CommandInterpreter &interpreter) 2494 : CommandObjectMultiword( 2495 interpreter, "target modules dump", 2496 "Commands for dumping information about one or " 2497 "more target modules.", 2498 "target modules dump " 2499 "[headers|symtab|sections|ast|symfile|line-table] " 2500 "[<file1> <file2> ...]") { 2501 LoadSubCommand("objfile", 2502 CommandObjectSP( 2503 new CommandObjectTargetModulesDumpObjfile(interpreter))); 2504 LoadSubCommand( 2505 "symtab", 2506 CommandObjectSP(new CommandObjectTargetModulesDumpSymtab(interpreter))); 2507 LoadSubCommand("sections", 2508 CommandObjectSP(new CommandObjectTargetModulesDumpSections( 2509 interpreter))); 2510 LoadSubCommand("symfile", 2511 CommandObjectSP( 2512 new CommandObjectTargetModulesDumpSymfile(interpreter))); 2513 LoadSubCommand( 2514 "ast", CommandObjectSP( 2515 new CommandObjectTargetModulesDumpClangAST(interpreter))); 2516 LoadSubCommand("line-table", 2517 CommandObjectSP(new CommandObjectTargetModulesDumpLineTable( 2518 interpreter))); 2519 } 2520 2521 ~CommandObjectTargetModulesDump() override = default; 2522 }; 2523 2524 class CommandObjectTargetModulesAdd : public CommandObjectParsed { 2525 public: 2526 CommandObjectTargetModulesAdd(CommandInterpreter &interpreter) 2527 : CommandObjectParsed(interpreter, "target modules add", 2528 "Add a new module to the current target's modules.", 2529 "target modules add [<module>]"), 2530 m_option_group(), 2531 m_symbol_file(LLDB_OPT_SET_1, false, "symfile", 's', 0, 2532 eArgTypeFilename, "Fullpath to a stand alone debug " 2533 "symbols file for when debug symbols " 2534 "are not in the executable.") { 2535 m_option_group.Append(&m_uuid_option_group, LLDB_OPT_SET_ALL, 2536 LLDB_OPT_SET_1); 2537 m_option_group.Append(&m_symbol_file, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); 2538 m_option_group.Finalize(); 2539 } 2540 2541 ~CommandObjectTargetModulesAdd() override = default; 2542 2543 Options *GetOptions() override { return &m_option_group; } 2544 2545 int HandleArgumentCompletion( 2546 CompletionRequest &request, 2547 OptionElementVector &opt_element_vector) override { 2548 CommandCompletions::InvokeCommonCompletionCallbacks( 2549 GetCommandInterpreter(), CommandCompletions::eDiskFileCompletion, 2550 request, nullptr); 2551 return request.GetNumberOfMatches(); 2552 } 2553 2554 protected: 2555 OptionGroupOptions m_option_group; 2556 OptionGroupUUID m_uuid_option_group; 2557 OptionGroupFile m_symbol_file; 2558 2559 bool DoExecute(Args &args, CommandReturnObject &result) override { 2560 Target *target = GetDebugger().GetSelectedTarget().get(); 2561 if (target == nullptr) { 2562 result.AppendError("invalid target, create a debug target using the " 2563 "'target create' command"); 2564 result.SetStatus(eReturnStatusFailed); 2565 return false; 2566 } else { 2567 bool flush = false; 2568 2569 const size_t argc = args.GetArgumentCount(); 2570 if (argc == 0) { 2571 if (m_uuid_option_group.GetOptionValue().OptionWasSet()) { 2572 // We are given a UUID only, go locate the file 2573 ModuleSpec module_spec; 2574 module_spec.GetUUID() = 2575 m_uuid_option_group.GetOptionValue().GetCurrentValue(); 2576 if (m_symbol_file.GetOptionValue().OptionWasSet()) 2577 module_spec.GetSymbolFileSpec() = 2578 m_symbol_file.GetOptionValue().GetCurrentValue(); 2579 if (Symbols::DownloadObjectAndSymbolFile(module_spec)) { 2580 ModuleSP module_sp(target->GetOrCreateModule(module_spec, 2581 true /* notify */)); 2582 if (module_sp) { 2583 result.SetStatus(eReturnStatusSuccessFinishResult); 2584 return true; 2585 } else { 2586 StreamString strm; 2587 module_spec.GetUUID().Dump(&strm); 2588 if (module_spec.GetFileSpec()) { 2589 if (module_spec.GetSymbolFileSpec()) { 2590 result.AppendErrorWithFormat( 2591 "Unable to create the executable or symbol file with " 2592 "UUID %s with path %s and symbol file %s", 2593 strm.GetData(), 2594 module_spec.GetFileSpec().GetPath().c_str(), 2595 module_spec.GetSymbolFileSpec().GetPath().c_str()); 2596 } else { 2597 result.AppendErrorWithFormat( 2598 "Unable to create the executable or symbol file with " 2599 "UUID %s with path %s", 2600 strm.GetData(), 2601 module_spec.GetFileSpec().GetPath().c_str()); 2602 } 2603 } else { 2604 result.AppendErrorWithFormat("Unable to create the executable " 2605 "or symbol file with UUID %s", 2606 strm.GetData()); 2607 } 2608 result.SetStatus(eReturnStatusFailed); 2609 return false; 2610 } 2611 } else { 2612 StreamString strm; 2613 module_spec.GetUUID().Dump(&strm); 2614 result.AppendErrorWithFormat( 2615 "Unable to locate the executable or symbol file with UUID %s", 2616 strm.GetData()); 2617 result.SetStatus(eReturnStatusFailed); 2618 return false; 2619 } 2620 } else { 2621 result.AppendError( 2622 "one or more executable image paths must be specified"); 2623 result.SetStatus(eReturnStatusFailed); 2624 return false; 2625 } 2626 } else { 2627 for (auto &entry : args.entries()) { 2628 if (entry.ref.empty()) 2629 continue; 2630 2631 FileSpec file_spec(entry.ref); 2632 if (FileSystem::Instance().Exists(file_spec)) { 2633 ModuleSpec module_spec(file_spec); 2634 if (m_uuid_option_group.GetOptionValue().OptionWasSet()) 2635 module_spec.GetUUID() = 2636 m_uuid_option_group.GetOptionValue().GetCurrentValue(); 2637 if (m_symbol_file.GetOptionValue().OptionWasSet()) 2638 module_spec.GetSymbolFileSpec() = 2639 m_symbol_file.GetOptionValue().GetCurrentValue(); 2640 if (!module_spec.GetArchitecture().IsValid()) 2641 module_spec.GetArchitecture() = target->GetArchitecture(); 2642 Status error; 2643 ModuleSP module_sp(target->GetOrCreateModule(module_spec, 2644 true /* notify */, &error)); 2645 if (!module_sp) { 2646 const char *error_cstr = error.AsCString(); 2647 if (error_cstr) 2648 result.AppendError(error_cstr); 2649 else 2650 result.AppendErrorWithFormat("unsupported module: %s", 2651 entry.c_str()); 2652 result.SetStatus(eReturnStatusFailed); 2653 return false; 2654 } else { 2655 flush = true; 2656 } 2657 result.SetStatus(eReturnStatusSuccessFinishResult); 2658 } else { 2659 std::string resolved_path = file_spec.GetPath(); 2660 result.SetStatus(eReturnStatusFailed); 2661 if (resolved_path != entry.ref) { 2662 result.AppendErrorWithFormat( 2663 "invalid module path '%s' with resolved path '%s'\n", 2664 entry.ref.str().c_str(), resolved_path.c_str()); 2665 break; 2666 } 2667 result.AppendErrorWithFormat("invalid module path '%s'\n", 2668 entry.c_str()); 2669 break; 2670 } 2671 } 2672 } 2673 2674 if (flush) { 2675 ProcessSP process = target->GetProcessSP(); 2676 if (process) 2677 process->Flush(); 2678 } 2679 } 2680 2681 return result.Succeeded(); 2682 } 2683 }; 2684 2685 class CommandObjectTargetModulesLoad 2686 : public CommandObjectTargetModulesModuleAutoComplete { 2687 public: 2688 CommandObjectTargetModulesLoad(CommandInterpreter &interpreter) 2689 : CommandObjectTargetModulesModuleAutoComplete( 2690 interpreter, "target modules load", "Set the load addresses for " 2691 "one or more sections in a " 2692 "target module.", 2693 "target modules load [--file <module> --uuid <uuid>] <sect-name> " 2694 "<address> [<sect-name> <address> ....]"), 2695 m_option_group(), 2696 m_file_option(LLDB_OPT_SET_1, false, "file", 'f', 0, eArgTypeName, 2697 "Fullpath or basename for module to load.", ""), 2698 m_load_option(LLDB_OPT_SET_1, false, "load", 'l', 2699 "Write file contents to the memory.", false, true), 2700 m_pc_option(LLDB_OPT_SET_1, false, "set-pc-to-entry", 'p', 2701 "Set PC to the entry point." 2702 " Only applicable with '--load' option.", 2703 false, true), 2704 m_slide_option(LLDB_OPT_SET_1, false, "slide", 's', 0, eArgTypeOffset, 2705 "Set the load address for all sections to be the " 2706 "virtual address in the file plus the offset.", 2707 0) { 2708 m_option_group.Append(&m_uuid_option_group, LLDB_OPT_SET_ALL, 2709 LLDB_OPT_SET_1); 2710 m_option_group.Append(&m_file_option, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); 2711 m_option_group.Append(&m_load_option, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); 2712 m_option_group.Append(&m_pc_option, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); 2713 m_option_group.Append(&m_slide_option, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); 2714 m_option_group.Finalize(); 2715 } 2716 2717 ~CommandObjectTargetModulesLoad() override = default; 2718 2719 Options *GetOptions() override { return &m_option_group; } 2720 2721 protected: 2722 bool DoExecute(Args &args, CommandReturnObject &result) override { 2723 Target *target = GetDebugger().GetSelectedTarget().get(); 2724 const bool load = m_load_option.GetOptionValue().GetCurrentValue(); 2725 const bool set_pc = m_pc_option.GetOptionValue().GetCurrentValue(); 2726 if (target == nullptr) { 2727 result.AppendError("invalid target, create a debug target using the " 2728 "'target create' command"); 2729 result.SetStatus(eReturnStatusFailed); 2730 return false; 2731 } else { 2732 const size_t argc = args.GetArgumentCount(); 2733 ModuleSpec module_spec; 2734 bool search_using_module_spec = false; 2735 2736 // Allow "load" option to work without --file or --uuid option. 2737 if (load) { 2738 if (!m_file_option.GetOptionValue().OptionWasSet() && 2739 !m_uuid_option_group.GetOptionValue().OptionWasSet()) { 2740 ModuleList &module_list = target->GetImages(); 2741 if (module_list.GetSize() == 1) { 2742 search_using_module_spec = true; 2743 module_spec.GetFileSpec() = 2744 module_list.GetModuleAtIndex(0)->GetFileSpec(); 2745 } 2746 } 2747 } 2748 2749 if (m_file_option.GetOptionValue().OptionWasSet()) { 2750 search_using_module_spec = true; 2751 const char *arg_cstr = m_file_option.GetOptionValue().GetCurrentValue(); 2752 const bool use_global_module_list = true; 2753 ModuleList module_list; 2754 const size_t num_matches = FindModulesByName( 2755 target, arg_cstr, module_list, use_global_module_list); 2756 if (num_matches == 1) { 2757 module_spec.GetFileSpec() = 2758 module_list.GetModuleAtIndex(0)->GetFileSpec(); 2759 } else if (num_matches > 1) { 2760 search_using_module_spec = false; 2761 result.AppendErrorWithFormat( 2762 "more than 1 module matched by name '%s'\n", arg_cstr); 2763 result.SetStatus(eReturnStatusFailed); 2764 } else { 2765 search_using_module_spec = false; 2766 result.AppendErrorWithFormat("no object file for module '%s'\n", 2767 arg_cstr); 2768 result.SetStatus(eReturnStatusFailed); 2769 } 2770 } 2771 2772 if (m_uuid_option_group.GetOptionValue().OptionWasSet()) { 2773 search_using_module_spec = true; 2774 module_spec.GetUUID() = 2775 m_uuid_option_group.GetOptionValue().GetCurrentValue(); 2776 } 2777 2778 if (search_using_module_spec) { 2779 ModuleList matching_modules; 2780 const size_t num_matches = 2781 target->GetImages().FindModules(module_spec, matching_modules); 2782 2783 char path[PATH_MAX]; 2784 if (num_matches == 1) { 2785 Module *module = matching_modules.GetModulePointerAtIndex(0); 2786 if (module) { 2787 ObjectFile *objfile = module->GetObjectFile(); 2788 if (objfile) { 2789 SectionList *section_list = module->GetSectionList(); 2790 if (section_list) { 2791 bool changed = false; 2792 if (argc == 0) { 2793 if (m_slide_option.GetOptionValue().OptionWasSet()) { 2794 const addr_t slide = 2795 m_slide_option.GetOptionValue().GetCurrentValue(); 2796 const bool slide_is_offset = true; 2797 module->SetLoadAddress(*target, slide, slide_is_offset, 2798 changed); 2799 } else { 2800 result.AppendError("one or more section name + load " 2801 "address pair must be specified"); 2802 result.SetStatus(eReturnStatusFailed); 2803 return false; 2804 } 2805 } else { 2806 if (m_slide_option.GetOptionValue().OptionWasSet()) { 2807 result.AppendError("The \"--slide <offset>\" option can't " 2808 "be used in conjunction with setting " 2809 "section load addresses.\n"); 2810 result.SetStatus(eReturnStatusFailed); 2811 return false; 2812 } 2813 2814 for (size_t i = 0; i < argc; i += 2) { 2815 const char *sect_name = args.GetArgumentAtIndex(i); 2816 const char *load_addr_cstr = args.GetArgumentAtIndex(i + 1); 2817 if (sect_name && load_addr_cstr) { 2818 ConstString const_sect_name(sect_name); 2819 bool success = false; 2820 addr_t load_addr = StringConvert::ToUInt64( 2821 load_addr_cstr, LLDB_INVALID_ADDRESS, 0, &success); 2822 if (success) { 2823 SectionSP section_sp( 2824 section_list->FindSectionByName(const_sect_name)); 2825 if (section_sp) { 2826 if (section_sp->IsThreadSpecific()) { 2827 result.AppendErrorWithFormat( 2828 "thread specific sections are not yet " 2829 "supported (section '%s')\n", 2830 sect_name); 2831 result.SetStatus(eReturnStatusFailed); 2832 break; 2833 } else { 2834 if (target->GetSectionLoadList() 2835 .SetSectionLoadAddress(section_sp, 2836 load_addr)) 2837 changed = true; 2838 result.AppendMessageWithFormat( 2839 "section '%s' loaded at 0x%" PRIx64 "\n", 2840 sect_name, load_addr); 2841 } 2842 } else { 2843 result.AppendErrorWithFormat("no section found that " 2844 "matches the section " 2845 "name '%s'\n", 2846 sect_name); 2847 result.SetStatus(eReturnStatusFailed); 2848 break; 2849 } 2850 } else { 2851 result.AppendErrorWithFormat( 2852 "invalid load address string '%s'\n", 2853 load_addr_cstr); 2854 result.SetStatus(eReturnStatusFailed); 2855 break; 2856 } 2857 } else { 2858 if (sect_name) 2859 result.AppendError("section names must be followed by " 2860 "a load address.\n"); 2861 else 2862 result.AppendError("one or more section name + load " 2863 "address pair must be specified.\n"); 2864 result.SetStatus(eReturnStatusFailed); 2865 break; 2866 } 2867 } 2868 } 2869 2870 if (changed) { 2871 target->ModulesDidLoad(matching_modules); 2872 Process *process = m_exe_ctx.GetProcessPtr(); 2873 if (process) 2874 process->Flush(); 2875 } 2876 if (load) { 2877 ProcessSP process = target->CalculateProcess(); 2878 Address file_entry = objfile->GetEntryPointAddress(); 2879 if (!process) { 2880 result.AppendError("No process"); 2881 return false; 2882 } 2883 if (set_pc && !file_entry.IsValid()) { 2884 result.AppendError("No entry address in object file"); 2885 return false; 2886 } 2887 std::vector<ObjectFile::LoadableData> loadables( 2888 objfile->GetLoadableData(*target)); 2889 if (loadables.size() == 0) { 2890 result.AppendError("No loadable sections"); 2891 return false; 2892 } 2893 Status error = process->WriteObjectFile(std::move(loadables)); 2894 if (error.Fail()) { 2895 result.AppendError(error.AsCString()); 2896 return false; 2897 } 2898 if (set_pc) { 2899 ThreadList &thread_list = process->GetThreadList(); 2900 RegisterContextSP reg_context( 2901 thread_list.GetSelectedThread()->GetRegisterContext()); 2902 addr_t file_entry_addr = file_entry.GetLoadAddress(target); 2903 if (!reg_context->SetPC(file_entry_addr)) { 2904 result.AppendErrorWithFormat("failed to set PC value to " 2905 "0x%" PRIx64 "\n", 2906 file_entry_addr); 2907 result.SetStatus(eReturnStatusFailed); 2908 } 2909 } 2910 } 2911 } else { 2912 module->GetFileSpec().GetPath(path, sizeof(path)); 2913 result.AppendErrorWithFormat( 2914 "no sections in object file '%s'\n", path); 2915 result.SetStatus(eReturnStatusFailed); 2916 } 2917 } else { 2918 module->GetFileSpec().GetPath(path, sizeof(path)); 2919 result.AppendErrorWithFormat("no object file for module '%s'\n", 2920 path); 2921 result.SetStatus(eReturnStatusFailed); 2922 } 2923 } else { 2924 FileSpec *module_spec_file = module_spec.GetFileSpecPtr(); 2925 if (module_spec_file) { 2926 module_spec_file->GetPath(path, sizeof(path)); 2927 result.AppendErrorWithFormat("invalid module '%s'.\n", path); 2928 } else 2929 result.AppendError("no module spec"); 2930 result.SetStatus(eReturnStatusFailed); 2931 } 2932 } else { 2933 std::string uuid_str; 2934 2935 if (module_spec.GetFileSpec()) 2936 module_spec.GetFileSpec().GetPath(path, sizeof(path)); 2937 else 2938 path[0] = '\0'; 2939 2940 if (module_spec.GetUUIDPtr()) 2941 uuid_str = module_spec.GetUUID().GetAsString(); 2942 if (num_matches > 1) { 2943 result.AppendErrorWithFormat( 2944 "multiple modules match%s%s%s%s:\n", path[0] ? " file=" : "", 2945 path, !uuid_str.empty() ? " uuid=" : "", uuid_str.c_str()); 2946 for (size_t i = 0; i < num_matches; ++i) { 2947 if (matching_modules.GetModulePointerAtIndex(i) 2948 ->GetFileSpec() 2949 .GetPath(path, sizeof(path))) 2950 result.AppendMessageWithFormat("%s\n", path); 2951 } 2952 } else { 2953 result.AppendErrorWithFormat( 2954 "no modules were found that match%s%s%s%s.\n", 2955 path[0] ? " file=" : "", path, 2956 !uuid_str.empty() ? " uuid=" : "", uuid_str.c_str()); 2957 } 2958 result.SetStatus(eReturnStatusFailed); 2959 } 2960 } else { 2961 result.AppendError("either the \"--file <module>\" or the \"--uuid " 2962 "<uuid>\" option must be specified.\n"); 2963 result.SetStatus(eReturnStatusFailed); 2964 return false; 2965 } 2966 } 2967 return result.Succeeded(); 2968 } 2969 2970 OptionGroupOptions m_option_group; 2971 OptionGroupUUID m_uuid_option_group; 2972 OptionGroupString m_file_option; 2973 OptionGroupBoolean m_load_option; 2974 OptionGroupBoolean m_pc_option; 2975 OptionGroupUInt64 m_slide_option; 2976 }; 2977 2978 // List images with associated information 2979 #define LLDB_OPTIONS_target_modules_list 2980 #include "CommandOptions.inc" 2981 2982 class CommandObjectTargetModulesList : public CommandObjectParsed { 2983 public: 2984 class CommandOptions : public Options { 2985 public: 2986 CommandOptions() 2987 : Options(), m_format_array(), m_use_global_module_list(false), 2988 m_module_addr(LLDB_INVALID_ADDRESS) {} 2989 2990 ~CommandOptions() override = default; 2991 2992 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, 2993 ExecutionContext *execution_context) override { 2994 Status error; 2995 2996 const int short_option = m_getopt_table[option_idx].val; 2997 if (short_option == 'g') { 2998 m_use_global_module_list = true; 2999 } else if (short_option == 'a') { 3000 m_module_addr = OptionArgParser::ToAddress( 3001 execution_context, option_arg, LLDB_INVALID_ADDRESS, &error); 3002 } else { 3003 unsigned long width = 0; 3004 option_arg.getAsInteger(0, width); 3005 m_format_array.push_back(std::make_pair(short_option, width)); 3006 } 3007 return error; 3008 } 3009 3010 void OptionParsingStarting(ExecutionContext *execution_context) override { 3011 m_format_array.clear(); 3012 m_use_global_module_list = false; 3013 m_module_addr = LLDB_INVALID_ADDRESS; 3014 } 3015 3016 llvm::ArrayRef<OptionDefinition> GetDefinitions() override { 3017 return llvm::makeArrayRef(g_target_modules_list_options); 3018 } 3019 3020 // Instance variables to hold the values for command options. 3021 typedef std::vector<std::pair<char, uint32_t>> FormatWidthCollection; 3022 FormatWidthCollection m_format_array; 3023 bool m_use_global_module_list; 3024 lldb::addr_t m_module_addr; 3025 }; 3026 3027 CommandObjectTargetModulesList(CommandInterpreter &interpreter) 3028 : CommandObjectParsed( 3029 interpreter, "target modules list", 3030 "List current executable and dependent shared library images.", 3031 "target modules list [<cmd-options>]"), 3032 m_options() {} 3033 3034 ~CommandObjectTargetModulesList() override = default; 3035 3036 Options *GetOptions() override { return &m_options; } 3037 3038 protected: 3039 bool DoExecute(Args &command, CommandReturnObject &result) override { 3040 Target *target = GetDebugger().GetSelectedTarget().get(); 3041 const bool use_global_module_list = m_options.m_use_global_module_list; 3042 // Define a local module list here to ensure it lives longer than any 3043 // "locker" object which might lock its contents below (through the 3044 // "module_list_ptr" variable). 3045 ModuleList module_list; 3046 if (target == nullptr && !use_global_module_list) { 3047 result.AppendError("invalid target, create a debug target using the " 3048 "'target create' command"); 3049 result.SetStatus(eReturnStatusFailed); 3050 return false; 3051 } else { 3052 if (target) { 3053 uint32_t addr_byte_size = 3054 target->GetArchitecture().GetAddressByteSize(); 3055 result.GetOutputStream().SetAddressByteSize(addr_byte_size); 3056 result.GetErrorStream().SetAddressByteSize(addr_byte_size); 3057 } 3058 // Dump all sections for all modules images 3059 Stream &strm = result.GetOutputStream(); 3060 3061 if (m_options.m_module_addr != LLDB_INVALID_ADDRESS) { 3062 if (target) { 3063 Address module_address; 3064 if (module_address.SetLoadAddress(m_options.m_module_addr, target)) { 3065 ModuleSP module_sp(module_address.GetModule()); 3066 if (module_sp) { 3067 PrintModule(target, module_sp.get(), 0, strm); 3068 result.SetStatus(eReturnStatusSuccessFinishResult); 3069 } else { 3070 result.AppendErrorWithFormat( 3071 "Couldn't find module matching address: 0x%" PRIx64 ".", 3072 m_options.m_module_addr); 3073 result.SetStatus(eReturnStatusFailed); 3074 } 3075 } else { 3076 result.AppendErrorWithFormat( 3077 "Couldn't find module containing address: 0x%" PRIx64 ".", 3078 m_options.m_module_addr); 3079 result.SetStatus(eReturnStatusFailed); 3080 } 3081 } else { 3082 result.AppendError( 3083 "Can only look up modules by address with a valid target."); 3084 result.SetStatus(eReturnStatusFailed); 3085 } 3086 return result.Succeeded(); 3087 } 3088 3089 size_t num_modules = 0; 3090 3091 // This locker will be locked on the mutex in module_list_ptr if it is 3092 // non-nullptr. Otherwise it will lock the 3093 // AllocationModuleCollectionMutex when accessing the global module list 3094 // directly. 3095 std::unique_lock<std::recursive_mutex> guard( 3096 Module::GetAllocationModuleCollectionMutex(), std::defer_lock); 3097 3098 const ModuleList *module_list_ptr = nullptr; 3099 const size_t argc = command.GetArgumentCount(); 3100 if (argc == 0) { 3101 if (use_global_module_list) { 3102 guard.lock(); 3103 num_modules = Module::GetNumberAllocatedModules(); 3104 } else { 3105 module_list_ptr = &target->GetImages(); 3106 } 3107 } else { 3108 // TODO: Convert to entry based iteration. Requires converting 3109 // FindModulesByName. 3110 for (size_t i = 0; i < argc; ++i) { 3111 // Dump specified images (by basename or fullpath) 3112 const char *arg_cstr = command.GetArgumentAtIndex(i); 3113 const size_t num_matches = FindModulesByName( 3114 target, arg_cstr, module_list, use_global_module_list); 3115 if (num_matches == 0) { 3116 if (argc == 1) { 3117 result.AppendErrorWithFormat("no modules found that match '%s'", 3118 arg_cstr); 3119 result.SetStatus(eReturnStatusFailed); 3120 return false; 3121 } 3122 } 3123 } 3124 3125 module_list_ptr = &module_list; 3126 } 3127 3128 std::unique_lock<std::recursive_mutex> lock; 3129 if (module_list_ptr != nullptr) { 3130 lock = 3131 std::unique_lock<std::recursive_mutex>(module_list_ptr->GetMutex()); 3132 3133 num_modules = module_list_ptr->GetSize(); 3134 } 3135 3136 if (num_modules > 0) { 3137 for (uint32_t image_idx = 0; image_idx < num_modules; ++image_idx) { 3138 ModuleSP module_sp; 3139 Module *module; 3140 if (module_list_ptr) { 3141 module_sp = module_list_ptr->GetModuleAtIndexUnlocked(image_idx); 3142 module = module_sp.get(); 3143 } else { 3144 module = Module::GetAllocatedModuleAtIndex(image_idx); 3145 module_sp = module->shared_from_this(); 3146 } 3147 3148 const size_t indent = strm.Printf("[%3u] ", image_idx); 3149 PrintModule(target, module, indent, strm); 3150 } 3151 result.SetStatus(eReturnStatusSuccessFinishResult); 3152 } else { 3153 if (argc) { 3154 if (use_global_module_list) 3155 result.AppendError( 3156 "the global module list has no matching modules"); 3157 else 3158 result.AppendError("the target has no matching modules"); 3159 } else { 3160 if (use_global_module_list) 3161 result.AppendError("the global module list is empty"); 3162 else 3163 result.AppendError( 3164 "the target has no associated executable images"); 3165 } 3166 result.SetStatus(eReturnStatusFailed); 3167 return false; 3168 } 3169 } 3170 return result.Succeeded(); 3171 } 3172 3173 void PrintModule(Target *target, Module *module, int indent, Stream &strm) { 3174 if (module == nullptr) { 3175 strm.PutCString("Null module"); 3176 return; 3177 } 3178 3179 bool dump_object_name = false; 3180 if (m_options.m_format_array.empty()) { 3181 m_options.m_format_array.push_back(std::make_pair('u', 0)); 3182 m_options.m_format_array.push_back(std::make_pair('h', 0)); 3183 m_options.m_format_array.push_back(std::make_pair('f', 0)); 3184 m_options.m_format_array.push_back(std::make_pair('S', 0)); 3185 } 3186 const size_t num_entries = m_options.m_format_array.size(); 3187 bool print_space = false; 3188 for (size_t i = 0; i < num_entries; ++i) { 3189 if (print_space) 3190 strm.PutChar(' '); 3191 print_space = true; 3192 const char format_char = m_options.m_format_array[i].first; 3193 uint32_t width = m_options.m_format_array[i].second; 3194 switch (format_char) { 3195 case 'A': 3196 DumpModuleArchitecture(strm, module, false, width); 3197 break; 3198 3199 case 't': 3200 DumpModuleArchitecture(strm, module, true, width); 3201 break; 3202 3203 case 'f': 3204 DumpFullpath(strm, &module->GetFileSpec(), width); 3205 dump_object_name = true; 3206 break; 3207 3208 case 'd': 3209 DumpDirectory(strm, &module->GetFileSpec(), width); 3210 break; 3211 3212 case 'b': 3213 DumpBasename(strm, &module->GetFileSpec(), width); 3214 dump_object_name = true; 3215 break; 3216 3217 case 'h': 3218 case 'o': 3219 // Image header address 3220 { 3221 uint32_t addr_nibble_width = 3222 target ? (target->GetArchitecture().GetAddressByteSize() * 2) 3223 : 16; 3224 3225 ObjectFile *objfile = module->GetObjectFile(); 3226 if (objfile) { 3227 Address base_addr(objfile->GetBaseAddress()); 3228 if (base_addr.IsValid()) { 3229 if (target && !target->GetSectionLoadList().IsEmpty()) { 3230 lldb::addr_t load_addr = 3231 base_addr.GetLoadAddress(target); 3232 if (load_addr == LLDB_INVALID_ADDRESS) { 3233 base_addr.Dump(&strm, target, 3234 Address::DumpStyleModuleWithFileAddress, 3235 Address::DumpStyleFileAddress); 3236 } else { 3237 if (format_char == 'o') { 3238 // Show the offset of slide for the image 3239 strm.Printf( 3240 "0x%*.*" PRIx64, addr_nibble_width, addr_nibble_width, 3241 load_addr - base_addr.GetFileAddress()); 3242 } else { 3243 // Show the load address of the image 3244 strm.Printf("0x%*.*" PRIx64, addr_nibble_width, 3245 addr_nibble_width, load_addr); 3246 } 3247 } 3248 break; 3249 } 3250 // The address was valid, but the image isn't loaded, output the 3251 // address in an appropriate format 3252 base_addr.Dump(&strm, target, Address::DumpStyleFileAddress); 3253 break; 3254 } 3255 } 3256 strm.Printf("%*s", addr_nibble_width + 2, ""); 3257 } 3258 break; 3259 3260 case 'r': { 3261 size_t ref_count = 0; 3262 ModuleSP module_sp(module->shared_from_this()); 3263 if (module_sp) { 3264 // Take one away to make sure we don't count our local "module_sp" 3265 ref_count = module_sp.use_count() - 1; 3266 } 3267 if (width) 3268 strm.Printf("{%*" PRIu64 "}", width, (uint64_t)ref_count); 3269 else 3270 strm.Printf("{%" PRIu64 "}", (uint64_t)ref_count); 3271 } break; 3272 3273 case 's': 3274 case 'S': { 3275 const SymbolVendor *symbol_vendor = module->GetSymbolVendor(); 3276 if (symbol_vendor) { 3277 const FileSpec symfile_spec = symbol_vendor->GetMainFileSpec(); 3278 if (format_char == 'S') { 3279 // Dump symbol file only if different from module file 3280 if (!symfile_spec || symfile_spec == module->GetFileSpec()) { 3281 print_space = false; 3282 break; 3283 } 3284 // Add a newline and indent past the index 3285 strm.Printf("\n%*s", indent, ""); 3286 } 3287 DumpFullpath(strm, &symfile_spec, width); 3288 dump_object_name = true; 3289 break; 3290 } 3291 strm.Printf("%.*s", width, "<NONE>"); 3292 } break; 3293 3294 case 'm': 3295 strm.Format("{0:%c}", llvm::fmt_align(module->GetModificationTime(), 3296 llvm::AlignStyle::Left, width)); 3297 break; 3298 3299 case 'p': 3300 strm.Printf("%p", static_cast<void *>(module)); 3301 break; 3302 3303 case 'u': 3304 DumpModuleUUID(strm, module); 3305 break; 3306 3307 default: 3308 break; 3309 } 3310 } 3311 if (dump_object_name) { 3312 const char *object_name = module->GetObjectName().GetCString(); 3313 if (object_name) 3314 strm.Printf("(%s)", object_name); 3315 } 3316 strm.EOL(); 3317 } 3318 3319 CommandOptions m_options; 3320 }; 3321 3322 #pragma mark CommandObjectTargetModulesShowUnwind 3323 3324 // Lookup unwind information in images 3325 #define LLDB_OPTIONS_target_modules_show_unwind 3326 #include "CommandOptions.inc" 3327 3328 class CommandObjectTargetModulesShowUnwind : public CommandObjectParsed { 3329 public: 3330 enum { 3331 eLookupTypeInvalid = -1, 3332 eLookupTypeAddress = 0, 3333 eLookupTypeSymbol, 3334 eLookupTypeFunction, 3335 eLookupTypeFunctionOrSymbol, 3336 kNumLookupTypes 3337 }; 3338 3339 class CommandOptions : public Options { 3340 public: 3341 CommandOptions() 3342 : Options(), m_type(eLookupTypeInvalid), m_str(), 3343 m_addr(LLDB_INVALID_ADDRESS) {} 3344 3345 ~CommandOptions() override = default; 3346 3347 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, 3348 ExecutionContext *execution_context) override { 3349 Status error; 3350 3351 const int short_option = m_getopt_table[option_idx].val; 3352 3353 switch (short_option) { 3354 case 'a': { 3355 m_str = option_arg; 3356 m_type = eLookupTypeAddress; 3357 m_addr = OptionArgParser::ToAddress(execution_context, option_arg, 3358 LLDB_INVALID_ADDRESS, &error); 3359 if (m_addr == LLDB_INVALID_ADDRESS) 3360 error.SetErrorStringWithFormat("invalid address string '%s'", 3361 option_arg.str().c_str()); 3362 break; 3363 } 3364 3365 case 'n': 3366 m_str = option_arg; 3367 m_type = eLookupTypeFunctionOrSymbol; 3368 break; 3369 3370 default: 3371 error.SetErrorStringWithFormat("unrecognized option %c.", short_option); 3372 break; 3373 } 3374 3375 return error; 3376 } 3377 3378 void OptionParsingStarting(ExecutionContext *execution_context) override { 3379 m_type = eLookupTypeInvalid; 3380 m_str.clear(); 3381 m_addr = LLDB_INVALID_ADDRESS; 3382 } 3383 3384 llvm::ArrayRef<OptionDefinition> GetDefinitions() override { 3385 return llvm::makeArrayRef(g_target_modules_show_unwind_options); 3386 } 3387 3388 // Instance variables to hold the values for command options. 3389 3390 int m_type; // Should be a eLookupTypeXXX enum after parsing options 3391 std::string m_str; // Holds name lookup 3392 lldb::addr_t m_addr; // Holds the address to lookup 3393 }; 3394 3395 CommandObjectTargetModulesShowUnwind(CommandInterpreter &interpreter) 3396 : CommandObjectParsed( 3397 interpreter, "target modules show-unwind", 3398 "Show synthesized unwind instructions for a function.", nullptr, 3399 eCommandRequiresTarget | eCommandRequiresProcess | 3400 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused), 3401 m_options() {} 3402 3403 ~CommandObjectTargetModulesShowUnwind() override = default; 3404 3405 Options *GetOptions() override { return &m_options; } 3406 3407 protected: 3408 bool DoExecute(Args &command, CommandReturnObject &result) override { 3409 Target *target = m_exe_ctx.GetTargetPtr(); 3410 Process *process = m_exe_ctx.GetProcessPtr(); 3411 ABI *abi = nullptr; 3412 if (process) 3413 abi = process->GetABI().get(); 3414 3415 if (process == nullptr) { 3416 result.AppendError( 3417 "You must have a process running to use this command."); 3418 result.SetStatus(eReturnStatusFailed); 3419 return false; 3420 } 3421 3422 ThreadList threads(process->GetThreadList()); 3423 if (threads.GetSize() == 0) { 3424 result.AppendError("The process must be paused to use this command."); 3425 result.SetStatus(eReturnStatusFailed); 3426 return false; 3427 } 3428 3429 ThreadSP thread(threads.GetThreadAtIndex(0)); 3430 if (!thread) { 3431 result.AppendError("The process must be paused to use this command."); 3432 result.SetStatus(eReturnStatusFailed); 3433 return false; 3434 } 3435 3436 SymbolContextList sc_list; 3437 3438 if (m_options.m_type == eLookupTypeFunctionOrSymbol) { 3439 ConstString function_name(m_options.m_str.c_str()); 3440 target->GetImages().FindFunctions(function_name, eFunctionNameTypeAuto, 3441 true, false, true, sc_list); 3442 } else if (m_options.m_type == eLookupTypeAddress && target) { 3443 Address addr; 3444 if (target->GetSectionLoadList().ResolveLoadAddress(m_options.m_addr, 3445 addr)) { 3446 SymbolContext sc; 3447 ModuleSP module_sp(addr.GetModule()); 3448 module_sp->ResolveSymbolContextForAddress(addr, 3449 eSymbolContextEverything, sc); 3450 if (sc.function || sc.symbol) { 3451 sc_list.Append(sc); 3452 } 3453 } 3454 } else { 3455 result.AppendError( 3456 "address-expression or function name option must be specified."); 3457 result.SetStatus(eReturnStatusFailed); 3458 return false; 3459 } 3460 3461 size_t num_matches = sc_list.GetSize(); 3462 if (num_matches == 0) { 3463 result.AppendErrorWithFormat("no unwind data found that matches '%s'.", 3464 m_options.m_str.c_str()); 3465 result.SetStatus(eReturnStatusFailed); 3466 return false; 3467 } 3468 3469 for (uint32_t idx = 0; idx < num_matches; idx++) { 3470 SymbolContext sc; 3471 sc_list.GetContextAtIndex(idx, sc); 3472 if (sc.symbol == nullptr && sc.function == nullptr) 3473 continue; 3474 if (!sc.module_sp || sc.module_sp->GetObjectFile() == nullptr) 3475 continue; 3476 AddressRange range; 3477 if (!sc.GetAddressRange(eSymbolContextFunction | eSymbolContextSymbol, 0, 3478 false, range)) 3479 continue; 3480 if (!range.GetBaseAddress().IsValid()) 3481 continue; 3482 ConstString funcname(sc.GetFunctionName()); 3483 if (funcname.IsEmpty()) 3484 continue; 3485 addr_t start_addr = range.GetBaseAddress().GetLoadAddress(target); 3486 if (abi) 3487 start_addr = abi->FixCodeAddress(start_addr); 3488 3489 FuncUnwindersSP func_unwinders_sp( 3490 sc.module_sp->GetUnwindTable() 3491 .GetUncachedFuncUnwindersContainingAddress(start_addr, sc)); 3492 if (!func_unwinders_sp) 3493 continue; 3494 3495 result.GetOutputStream().Printf( 3496 "UNWIND PLANS for %s`%s (start addr 0x%" PRIx64 ")\n\n", 3497 sc.module_sp->GetPlatformFileSpec().GetFilename().AsCString(), 3498 funcname.AsCString(), start_addr); 3499 3500 UnwindPlanSP non_callsite_unwind_plan = 3501 func_unwinders_sp->GetUnwindPlanAtNonCallSite(*target, *thread); 3502 if (non_callsite_unwind_plan) { 3503 result.GetOutputStream().Printf( 3504 "Asynchronous (not restricted to call-sites) UnwindPlan is '%s'\n", 3505 non_callsite_unwind_plan->GetSourceName().AsCString()); 3506 } 3507 UnwindPlanSP callsite_unwind_plan = 3508 func_unwinders_sp->GetUnwindPlanAtCallSite(*target, *thread); 3509 if (callsite_unwind_plan) { 3510 result.GetOutputStream().Printf( 3511 "Synchronous (restricted to call-sites) UnwindPlan is '%s'\n", 3512 callsite_unwind_plan->GetSourceName().AsCString()); 3513 } 3514 UnwindPlanSP fast_unwind_plan = 3515 func_unwinders_sp->GetUnwindPlanFastUnwind(*target, *thread); 3516 if (fast_unwind_plan) { 3517 result.GetOutputStream().Printf( 3518 "Fast UnwindPlan is '%s'\n", 3519 fast_unwind_plan->GetSourceName().AsCString()); 3520 } 3521 3522 result.GetOutputStream().Printf("\n"); 3523 3524 UnwindPlanSP assembly_sp = 3525 func_unwinders_sp->GetAssemblyUnwindPlan(*target, *thread); 3526 if (assembly_sp) { 3527 result.GetOutputStream().Printf( 3528 "Assembly language inspection UnwindPlan:\n"); 3529 assembly_sp->Dump(result.GetOutputStream(), thread.get(), 3530 LLDB_INVALID_ADDRESS); 3531 result.GetOutputStream().Printf("\n"); 3532 } 3533 3534 UnwindPlanSP ehframe_sp = 3535 func_unwinders_sp->GetEHFrameUnwindPlan(*target); 3536 if (ehframe_sp) { 3537 result.GetOutputStream().Printf("eh_frame UnwindPlan:\n"); 3538 ehframe_sp->Dump(result.GetOutputStream(), thread.get(), 3539 LLDB_INVALID_ADDRESS); 3540 result.GetOutputStream().Printf("\n"); 3541 } 3542 3543 UnwindPlanSP ehframe_augmented_sp = 3544 func_unwinders_sp->GetEHFrameAugmentedUnwindPlan(*target, *thread); 3545 if (ehframe_augmented_sp) { 3546 result.GetOutputStream().Printf("eh_frame augmented UnwindPlan:\n"); 3547 ehframe_augmented_sp->Dump(result.GetOutputStream(), thread.get(), 3548 LLDB_INVALID_ADDRESS); 3549 result.GetOutputStream().Printf("\n"); 3550 } 3551 3552 if (UnwindPlanSP plan_sp = 3553 func_unwinders_sp->GetDebugFrameUnwindPlan(*target)) { 3554 result.GetOutputStream().Printf("debug_frame UnwindPlan:\n"); 3555 plan_sp->Dump(result.GetOutputStream(), thread.get(), 3556 LLDB_INVALID_ADDRESS); 3557 result.GetOutputStream().Printf("\n"); 3558 } 3559 3560 if (UnwindPlanSP plan_sp = 3561 func_unwinders_sp->GetDebugFrameAugmentedUnwindPlan(*target, 3562 *thread)) { 3563 result.GetOutputStream().Printf("debug_frame augmented UnwindPlan:\n"); 3564 plan_sp->Dump(result.GetOutputStream(), thread.get(), 3565 LLDB_INVALID_ADDRESS); 3566 result.GetOutputStream().Printf("\n"); 3567 } 3568 3569 UnwindPlanSP arm_unwind_sp = 3570 func_unwinders_sp->GetArmUnwindUnwindPlan(*target); 3571 if (arm_unwind_sp) { 3572 result.GetOutputStream().Printf("ARM.exidx unwind UnwindPlan:\n"); 3573 arm_unwind_sp->Dump(result.GetOutputStream(), thread.get(), 3574 LLDB_INVALID_ADDRESS); 3575 result.GetOutputStream().Printf("\n"); 3576 } 3577 3578 if (UnwindPlanSP symfile_plan_sp = 3579 func_unwinders_sp->GetSymbolFileUnwindPlan(*thread)) { 3580 result.GetOutputStream().Printf("Symbol file UnwindPlan:\n"); 3581 symfile_plan_sp->Dump(result.GetOutputStream(), thread.get(), 3582 LLDB_INVALID_ADDRESS); 3583 result.GetOutputStream().Printf("\n"); 3584 } 3585 3586 UnwindPlanSP compact_unwind_sp = 3587 func_unwinders_sp->GetCompactUnwindUnwindPlan(*target); 3588 if (compact_unwind_sp) { 3589 result.GetOutputStream().Printf("Compact unwind UnwindPlan:\n"); 3590 compact_unwind_sp->Dump(result.GetOutputStream(), thread.get(), 3591 LLDB_INVALID_ADDRESS); 3592 result.GetOutputStream().Printf("\n"); 3593 } 3594 3595 if (fast_unwind_plan) { 3596 result.GetOutputStream().Printf("Fast UnwindPlan:\n"); 3597 fast_unwind_plan->Dump(result.GetOutputStream(), thread.get(), 3598 LLDB_INVALID_ADDRESS); 3599 result.GetOutputStream().Printf("\n"); 3600 } 3601 3602 ABISP abi_sp = process->GetABI(); 3603 if (abi_sp) { 3604 UnwindPlan arch_default(lldb::eRegisterKindGeneric); 3605 if (abi_sp->CreateDefaultUnwindPlan(arch_default)) { 3606 result.GetOutputStream().Printf("Arch default UnwindPlan:\n"); 3607 arch_default.Dump(result.GetOutputStream(), thread.get(), 3608 LLDB_INVALID_ADDRESS); 3609 result.GetOutputStream().Printf("\n"); 3610 } 3611 3612 UnwindPlan arch_entry(lldb::eRegisterKindGeneric); 3613 if (abi_sp->CreateFunctionEntryUnwindPlan(arch_entry)) { 3614 result.GetOutputStream().Printf( 3615 "Arch default at entry point UnwindPlan:\n"); 3616 arch_entry.Dump(result.GetOutputStream(), thread.get(), 3617 LLDB_INVALID_ADDRESS); 3618 result.GetOutputStream().Printf("\n"); 3619 } 3620 } 3621 3622 result.GetOutputStream().Printf("\n"); 3623 } 3624 return result.Succeeded(); 3625 } 3626 3627 CommandOptions m_options; 3628 }; 3629 3630 // Lookup information in images 3631 #define LLDB_OPTIONS_target_modules_lookup 3632 #include "CommandOptions.inc" 3633 3634 class CommandObjectTargetModulesLookup : public CommandObjectParsed { 3635 public: 3636 enum { 3637 eLookupTypeInvalid = -1, 3638 eLookupTypeAddress = 0, 3639 eLookupTypeSymbol, 3640 eLookupTypeFileLine, // Line is optional 3641 eLookupTypeFunction, 3642 eLookupTypeFunctionOrSymbol, 3643 eLookupTypeType, 3644 kNumLookupTypes 3645 }; 3646 3647 class CommandOptions : public Options { 3648 public: 3649 CommandOptions() : Options() { OptionParsingStarting(nullptr); } 3650 3651 ~CommandOptions() override = default; 3652 3653 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, 3654 ExecutionContext *execution_context) override { 3655 Status error; 3656 3657 const int short_option = m_getopt_table[option_idx].val; 3658 3659 switch (short_option) { 3660 case 'a': { 3661 m_type = eLookupTypeAddress; 3662 m_addr = OptionArgParser::ToAddress(execution_context, option_arg, 3663 LLDB_INVALID_ADDRESS, &error); 3664 } break; 3665 3666 case 'o': 3667 if (option_arg.getAsInteger(0, m_offset)) 3668 error.SetErrorStringWithFormat("invalid offset string '%s'", 3669 option_arg.str().c_str()); 3670 break; 3671 3672 case 's': 3673 m_str = option_arg; 3674 m_type = eLookupTypeSymbol; 3675 break; 3676 3677 case 'f': 3678 m_file.SetFile(option_arg, FileSpec::Style::native); 3679 m_type = eLookupTypeFileLine; 3680 break; 3681 3682 case 'i': 3683 m_include_inlines = false; 3684 break; 3685 3686 case 'l': 3687 if (option_arg.getAsInteger(0, m_line_number)) 3688 error.SetErrorStringWithFormat("invalid line number string '%s'", 3689 option_arg.str().c_str()); 3690 else if (m_line_number == 0) 3691 error.SetErrorString("zero is an invalid line number"); 3692 m_type = eLookupTypeFileLine; 3693 break; 3694 3695 case 'F': 3696 m_str = option_arg; 3697 m_type = eLookupTypeFunction; 3698 break; 3699 3700 case 'n': 3701 m_str = option_arg; 3702 m_type = eLookupTypeFunctionOrSymbol; 3703 break; 3704 3705 case 't': 3706 m_str = option_arg; 3707 m_type = eLookupTypeType; 3708 break; 3709 3710 case 'v': 3711 m_verbose = true; 3712 break; 3713 3714 case 'A': 3715 m_print_all = true; 3716 break; 3717 3718 case 'r': 3719 m_use_regex = true; 3720 break; 3721 } 3722 3723 return error; 3724 } 3725 3726 void OptionParsingStarting(ExecutionContext *execution_context) override { 3727 m_type = eLookupTypeInvalid; 3728 m_str.clear(); 3729 m_file.Clear(); 3730 m_addr = LLDB_INVALID_ADDRESS; 3731 m_offset = 0; 3732 m_line_number = 0; 3733 m_use_regex = false; 3734 m_include_inlines = true; 3735 m_verbose = false; 3736 m_print_all = false; 3737 } 3738 3739 llvm::ArrayRef<OptionDefinition> GetDefinitions() override { 3740 return llvm::makeArrayRef(g_target_modules_lookup_options); 3741 } 3742 3743 int m_type; // Should be a eLookupTypeXXX enum after parsing options 3744 std::string m_str; // Holds name lookup 3745 FileSpec m_file; // Files for file lookups 3746 lldb::addr_t m_addr; // Holds the address to lookup 3747 lldb::addr_t 3748 m_offset; // Subtract this offset from m_addr before doing lookups. 3749 uint32_t m_line_number; // Line number for file+line lookups 3750 bool m_use_regex; // Name lookups in m_str are regular expressions. 3751 bool m_include_inlines; // Check for inline entries when looking up by 3752 // file/line. 3753 bool m_verbose; // Enable verbose lookup info 3754 bool m_print_all; // Print all matches, even in cases where there's a best 3755 // match. 3756 }; 3757 3758 CommandObjectTargetModulesLookup(CommandInterpreter &interpreter) 3759 : CommandObjectParsed(interpreter, "target modules lookup", 3760 "Look up information within executable and " 3761 "dependent shared library images.", 3762 nullptr, eCommandRequiresTarget), 3763 m_options() { 3764 CommandArgumentEntry arg; 3765 CommandArgumentData file_arg; 3766 3767 // Define the first (and only) variant of this arg. 3768 file_arg.arg_type = eArgTypeFilename; 3769 file_arg.arg_repetition = eArgRepeatStar; 3770 3771 // There is only one variant this argument could be; put it into the 3772 // argument entry. 3773 arg.push_back(file_arg); 3774 3775 // Push the data for the first argument into the m_arguments vector. 3776 m_arguments.push_back(arg); 3777 } 3778 3779 ~CommandObjectTargetModulesLookup() override = default; 3780 3781 Options *GetOptions() override { return &m_options; } 3782 3783 bool LookupHere(CommandInterpreter &interpreter, CommandReturnObject &result, 3784 bool &syntax_error) { 3785 switch (m_options.m_type) { 3786 case eLookupTypeAddress: 3787 case eLookupTypeFileLine: 3788 case eLookupTypeFunction: 3789 case eLookupTypeFunctionOrSymbol: 3790 case eLookupTypeSymbol: 3791 default: 3792 return false; 3793 case eLookupTypeType: 3794 break; 3795 } 3796 3797 StackFrameSP frame = m_exe_ctx.GetFrameSP(); 3798 3799 if (!frame) 3800 return false; 3801 3802 const SymbolContext &sym_ctx(frame->GetSymbolContext(eSymbolContextModule)); 3803 3804 if (!sym_ctx.module_sp) 3805 return false; 3806 3807 switch (m_options.m_type) { 3808 default: 3809 return false; 3810 case eLookupTypeType: 3811 if (!m_options.m_str.empty()) { 3812 if (LookupTypeHere(m_interpreter, result.GetOutputStream(), 3813 *sym_ctx.module_sp, m_options.m_str.c_str(), 3814 m_options.m_use_regex)) { 3815 result.SetStatus(eReturnStatusSuccessFinishResult); 3816 return true; 3817 } 3818 } 3819 break; 3820 } 3821 3822 return true; 3823 } 3824 3825 bool LookupInModule(CommandInterpreter &interpreter, Module *module, 3826 CommandReturnObject &result, bool &syntax_error) { 3827 switch (m_options.m_type) { 3828 case eLookupTypeAddress: 3829 if (m_options.m_addr != LLDB_INVALID_ADDRESS) { 3830 if (LookupAddressInModule( 3831 m_interpreter, result.GetOutputStream(), module, 3832 eSymbolContextEverything | 3833 (m_options.m_verbose 3834 ? static_cast<int>(eSymbolContextVariable) 3835 : 0), 3836 m_options.m_addr, m_options.m_offset, m_options.m_verbose)) { 3837 result.SetStatus(eReturnStatusSuccessFinishResult); 3838 return true; 3839 } 3840 } 3841 break; 3842 3843 case eLookupTypeSymbol: 3844 if (!m_options.m_str.empty()) { 3845 if (LookupSymbolInModule(m_interpreter, result.GetOutputStream(), 3846 module, m_options.m_str.c_str(), 3847 m_options.m_use_regex, m_options.m_verbose)) { 3848 result.SetStatus(eReturnStatusSuccessFinishResult); 3849 return true; 3850 } 3851 } 3852 break; 3853 3854 case eLookupTypeFileLine: 3855 if (m_options.m_file) { 3856 if (LookupFileAndLineInModule( 3857 m_interpreter, result.GetOutputStream(), module, 3858 m_options.m_file, m_options.m_line_number, 3859 m_options.m_include_inlines, m_options.m_verbose)) { 3860 result.SetStatus(eReturnStatusSuccessFinishResult); 3861 return true; 3862 } 3863 } 3864 break; 3865 3866 case eLookupTypeFunctionOrSymbol: 3867 case eLookupTypeFunction: 3868 if (!m_options.m_str.empty()) { 3869 if (LookupFunctionInModule( 3870 m_interpreter, result.GetOutputStream(), module, 3871 m_options.m_str.c_str(), m_options.m_use_regex, 3872 m_options.m_include_inlines, 3873 m_options.m_type == 3874 eLookupTypeFunctionOrSymbol, // include symbols 3875 m_options.m_verbose)) { 3876 result.SetStatus(eReturnStatusSuccessFinishResult); 3877 return true; 3878 } 3879 } 3880 break; 3881 3882 case eLookupTypeType: 3883 if (!m_options.m_str.empty()) { 3884 if (LookupTypeInModule(m_interpreter, result.GetOutputStream(), module, 3885 m_options.m_str.c_str(), 3886 m_options.m_use_regex)) { 3887 result.SetStatus(eReturnStatusSuccessFinishResult); 3888 return true; 3889 } 3890 } 3891 break; 3892 3893 default: 3894 m_options.GenerateOptionUsage( 3895 result.GetErrorStream(), this, 3896 GetCommandInterpreter().GetDebugger().GetTerminalWidth()); 3897 syntax_error = true; 3898 break; 3899 } 3900 3901 result.SetStatus(eReturnStatusFailed); 3902 return false; 3903 } 3904 3905 protected: 3906 bool DoExecute(Args &command, CommandReturnObject &result) override { 3907 Target *target = GetDebugger().GetSelectedTarget().get(); 3908 if (target == nullptr) { 3909 result.AppendError("invalid target, create a debug target using the " 3910 "'target create' command"); 3911 result.SetStatus(eReturnStatusFailed); 3912 return false; 3913 } else { 3914 bool syntax_error = false; 3915 uint32_t i; 3916 uint32_t num_successful_lookups = 0; 3917 uint32_t addr_byte_size = target->GetArchitecture().GetAddressByteSize(); 3918 result.GetOutputStream().SetAddressByteSize(addr_byte_size); 3919 result.GetErrorStream().SetAddressByteSize(addr_byte_size); 3920 // Dump all sections for all modules images 3921 3922 if (command.GetArgumentCount() == 0) { 3923 ModuleSP current_module; 3924 3925 // Where it is possible to look in the current symbol context first, 3926 // try that. If this search was successful and --all was not passed, 3927 // don't print anything else. 3928 if (LookupHere(m_interpreter, result, syntax_error)) { 3929 result.GetOutputStream().EOL(); 3930 num_successful_lookups++; 3931 if (!m_options.m_print_all) { 3932 result.SetStatus(eReturnStatusSuccessFinishResult); 3933 return result.Succeeded(); 3934 } 3935 } 3936 3937 // Dump all sections for all other modules 3938 3939 const ModuleList &target_modules = target->GetImages(); 3940 std::lock_guard<std::recursive_mutex> guard(target_modules.GetMutex()); 3941 const size_t num_modules = target_modules.GetSize(); 3942 if (num_modules > 0) { 3943 for (i = 0; i < num_modules && !syntax_error; ++i) { 3944 Module *module_pointer = 3945 target_modules.GetModulePointerAtIndexUnlocked(i); 3946 3947 if (module_pointer != current_module.get() && 3948 LookupInModule( 3949 m_interpreter, 3950 target_modules.GetModulePointerAtIndexUnlocked(i), result, 3951 syntax_error)) { 3952 result.GetOutputStream().EOL(); 3953 num_successful_lookups++; 3954 } 3955 } 3956 } else { 3957 result.AppendError("the target has no associated executable images"); 3958 result.SetStatus(eReturnStatusFailed); 3959 return false; 3960 } 3961 } else { 3962 // Dump specified images (by basename or fullpath) 3963 const char *arg_cstr; 3964 for (i = 0; (arg_cstr = command.GetArgumentAtIndex(i)) != nullptr && 3965 !syntax_error; 3966 ++i) { 3967 ModuleList module_list; 3968 const size_t num_matches = 3969 FindModulesByName(target, arg_cstr, module_list, false); 3970 if (num_matches > 0) { 3971 for (size_t j = 0; j < num_matches; ++j) { 3972 Module *module = module_list.GetModulePointerAtIndex(j); 3973 if (module) { 3974 if (LookupInModule(m_interpreter, module, result, 3975 syntax_error)) { 3976 result.GetOutputStream().EOL(); 3977 num_successful_lookups++; 3978 } 3979 } 3980 } 3981 } else 3982 result.AppendWarningWithFormat( 3983 "Unable to find an image that matches '%s'.\n", arg_cstr); 3984 } 3985 } 3986 3987 if (num_successful_lookups > 0) 3988 result.SetStatus(eReturnStatusSuccessFinishResult); 3989 else 3990 result.SetStatus(eReturnStatusFailed); 3991 } 3992 return result.Succeeded(); 3993 } 3994 3995 CommandOptions m_options; 3996 }; 3997 3998 #pragma mark CommandObjectMultiwordImageSearchPaths 3999 4000 // CommandObjectMultiwordImageSearchPaths 4001 4002 class CommandObjectTargetModulesImageSearchPaths 4003 : public CommandObjectMultiword { 4004 public: 4005 CommandObjectTargetModulesImageSearchPaths(CommandInterpreter &interpreter) 4006 : CommandObjectMultiword( 4007 interpreter, "target modules search-paths", 4008 "Commands for managing module search paths for a target.", 4009 "target modules search-paths <subcommand> [<subcommand-options>]") { 4010 LoadSubCommand( 4011 "add", CommandObjectSP( 4012 new CommandObjectTargetModulesSearchPathsAdd(interpreter))); 4013 LoadSubCommand( 4014 "clear", CommandObjectSP(new CommandObjectTargetModulesSearchPathsClear( 4015 interpreter))); 4016 LoadSubCommand( 4017 "insert", 4018 CommandObjectSP( 4019 new CommandObjectTargetModulesSearchPathsInsert(interpreter))); 4020 LoadSubCommand( 4021 "list", CommandObjectSP(new CommandObjectTargetModulesSearchPathsList( 4022 interpreter))); 4023 LoadSubCommand( 4024 "query", CommandObjectSP(new CommandObjectTargetModulesSearchPathsQuery( 4025 interpreter))); 4026 } 4027 4028 ~CommandObjectTargetModulesImageSearchPaths() override = default; 4029 }; 4030 4031 #pragma mark CommandObjectTargetModules 4032 4033 // CommandObjectTargetModules 4034 4035 class CommandObjectTargetModules : public CommandObjectMultiword { 4036 public: 4037 // Constructors and Destructors 4038 CommandObjectTargetModules(CommandInterpreter &interpreter) 4039 : CommandObjectMultiword(interpreter, "target modules", 4040 "Commands for accessing information for one or " 4041 "more target modules.", 4042 "target modules <sub-command> ...") { 4043 LoadSubCommand( 4044 "add", CommandObjectSP(new CommandObjectTargetModulesAdd(interpreter))); 4045 LoadSubCommand("load", CommandObjectSP(new CommandObjectTargetModulesLoad( 4046 interpreter))); 4047 LoadSubCommand("dump", CommandObjectSP(new CommandObjectTargetModulesDump( 4048 interpreter))); 4049 LoadSubCommand("list", CommandObjectSP(new CommandObjectTargetModulesList( 4050 interpreter))); 4051 LoadSubCommand( 4052 "lookup", 4053 CommandObjectSP(new CommandObjectTargetModulesLookup(interpreter))); 4054 LoadSubCommand( 4055 "search-paths", 4056 CommandObjectSP( 4057 new CommandObjectTargetModulesImageSearchPaths(interpreter))); 4058 LoadSubCommand( 4059 "show-unwind", 4060 CommandObjectSP(new CommandObjectTargetModulesShowUnwind(interpreter))); 4061 } 4062 4063 ~CommandObjectTargetModules() override = default; 4064 4065 private: 4066 // For CommandObjectTargetModules only 4067 DISALLOW_COPY_AND_ASSIGN(CommandObjectTargetModules); 4068 }; 4069 4070 class CommandObjectTargetSymbolsAdd : public CommandObjectParsed { 4071 public: 4072 CommandObjectTargetSymbolsAdd(CommandInterpreter &interpreter) 4073 : CommandObjectParsed( 4074 interpreter, "target symbols add", 4075 "Add a debug symbol file to one of the target's current modules by " 4076 "specifying a path to a debug symbols file, or using the options " 4077 "to specify a module to download symbols for.", 4078 "target symbols add <cmd-options> [<symfile>]", 4079 eCommandRequiresTarget), 4080 m_option_group(), 4081 m_file_option( 4082 LLDB_OPT_SET_1, false, "shlib", 's', 4083 CommandCompletions::eModuleCompletion, eArgTypeShlibName, 4084 "Fullpath or basename for module to find debug symbols for."), 4085 m_current_frame_option( 4086 LLDB_OPT_SET_2, false, "frame", 'F', 4087 "Locate the debug symbols the currently selected frame.", false, 4088 true) 4089 4090 { 4091 m_option_group.Append(&m_uuid_option_group, LLDB_OPT_SET_ALL, 4092 LLDB_OPT_SET_1); 4093 m_option_group.Append(&m_file_option, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); 4094 m_option_group.Append(&m_current_frame_option, LLDB_OPT_SET_2, 4095 LLDB_OPT_SET_2); 4096 m_option_group.Finalize(); 4097 } 4098 4099 ~CommandObjectTargetSymbolsAdd() override = default; 4100 4101 int HandleArgumentCompletion( 4102 CompletionRequest &request, 4103 OptionElementVector &opt_element_vector) override { 4104 CommandCompletions::InvokeCommonCompletionCallbacks( 4105 GetCommandInterpreter(), CommandCompletions::eDiskFileCompletion, 4106 request, nullptr); 4107 return request.GetNumberOfMatches(); 4108 } 4109 4110 Options *GetOptions() override { return &m_option_group; } 4111 4112 protected: 4113 bool AddModuleSymbols(Target *target, ModuleSpec &module_spec, bool &flush, 4114 CommandReturnObject &result) { 4115 const FileSpec &symbol_fspec = module_spec.GetSymbolFileSpec(); 4116 if (symbol_fspec) { 4117 char symfile_path[PATH_MAX]; 4118 symbol_fspec.GetPath(symfile_path, sizeof(symfile_path)); 4119 4120 if (!module_spec.GetUUID().IsValid()) { 4121 if (!module_spec.GetFileSpec() && !module_spec.GetPlatformFileSpec()) 4122 module_spec.GetFileSpec().GetFilename() = symbol_fspec.GetFilename(); 4123 } 4124 // We now have a module that represents a symbol file that can be used 4125 // for a module that might exist in the current target, so we need to 4126 // find that module in the target 4127 ModuleList matching_module_list; 4128 4129 size_t num_matches = 0; 4130 // First extract all module specs from the symbol file 4131 lldb_private::ModuleSpecList symfile_module_specs; 4132 if (ObjectFile::GetModuleSpecifications(module_spec.GetSymbolFileSpec(), 4133 0, 0, symfile_module_specs)) { 4134 // Now extract the module spec that matches the target architecture 4135 ModuleSpec target_arch_module_spec; 4136 ModuleSpec symfile_module_spec; 4137 target_arch_module_spec.GetArchitecture() = target->GetArchitecture(); 4138 if (symfile_module_specs.FindMatchingModuleSpec(target_arch_module_spec, 4139 symfile_module_spec)) { 4140 // See if it has a UUID? 4141 if (symfile_module_spec.GetUUID().IsValid()) { 4142 // It has a UUID, look for this UUID in the target modules 4143 ModuleSpec symfile_uuid_module_spec; 4144 symfile_uuid_module_spec.GetUUID() = symfile_module_spec.GetUUID(); 4145 num_matches = target->GetImages().FindModules( 4146 symfile_uuid_module_spec, matching_module_list); 4147 } 4148 } 4149 4150 if (num_matches == 0) { 4151 // No matches yet, iterate through the module specs to find a UUID 4152 // value that we can match up to an image in our target 4153 const size_t num_symfile_module_specs = 4154 symfile_module_specs.GetSize(); 4155 for (size_t i = 0; i < num_symfile_module_specs && num_matches == 0; 4156 ++i) { 4157 if (symfile_module_specs.GetModuleSpecAtIndex( 4158 i, symfile_module_spec)) { 4159 if (symfile_module_spec.GetUUID().IsValid()) { 4160 // It has a UUID, look for this UUID in the target modules 4161 ModuleSpec symfile_uuid_module_spec; 4162 symfile_uuid_module_spec.GetUUID() = 4163 symfile_module_spec.GetUUID(); 4164 num_matches = target->GetImages().FindModules( 4165 symfile_uuid_module_spec, matching_module_list); 4166 } 4167 } 4168 } 4169 } 4170 } 4171 4172 // Just try to match up the file by basename if we have no matches at 4173 // this point 4174 if (num_matches == 0) 4175 num_matches = 4176 target->GetImages().FindModules(module_spec, matching_module_list); 4177 4178 while (num_matches == 0) { 4179 ConstString filename_no_extension( 4180 module_spec.GetFileSpec().GetFileNameStrippingExtension()); 4181 // Empty string returned, lets bail 4182 if (!filename_no_extension) 4183 break; 4184 4185 // Check if there was no extension to strip and the basename is the 4186 // same 4187 if (filename_no_extension == module_spec.GetFileSpec().GetFilename()) 4188 break; 4189 4190 // Replace basename with one less extension 4191 module_spec.GetFileSpec().GetFilename() = filename_no_extension; 4192 4193 num_matches = 4194 target->GetImages().FindModules(module_spec, matching_module_list); 4195 } 4196 4197 if (num_matches > 1) { 4198 result.AppendErrorWithFormat("multiple modules match symbol file '%s', " 4199 "use the --uuid option to resolve the " 4200 "ambiguity.\n", 4201 symfile_path); 4202 } else if (num_matches == 1) { 4203 ModuleSP module_sp(matching_module_list.GetModuleAtIndex(0)); 4204 4205 // The module has not yet created its symbol vendor, we can just give 4206 // the existing target module the symfile path to use for when it 4207 // decides to create it! 4208 module_sp->SetSymbolFileFileSpec(symbol_fspec); 4209 4210 SymbolVendor *symbol_vendor = 4211 module_sp->GetSymbolVendor(true, &result.GetErrorStream()); 4212 if (symbol_vendor) { 4213 SymbolFile *symbol_file = symbol_vendor->GetSymbolFile(); 4214 4215 if (symbol_file) { 4216 ObjectFile *object_file = symbol_file->GetObjectFile(); 4217 4218 if (object_file && object_file->GetFileSpec() == symbol_fspec) { 4219 // Provide feedback that the symfile has been successfully added. 4220 const FileSpec &module_fs = module_sp->GetFileSpec(); 4221 result.AppendMessageWithFormat( 4222 "symbol file '%s' has been added to '%s'\n", symfile_path, 4223 module_fs.GetPath().c_str()); 4224 4225 // Let clients know something changed in the module if it is 4226 // currently loaded 4227 ModuleList module_list; 4228 module_list.Append(module_sp); 4229 target->SymbolsDidLoad(module_list); 4230 4231 // Make sure we load any scripting resources that may be embedded 4232 // in the debug info files in case the platform supports that. 4233 Status error; 4234 StreamString feedback_stream; 4235 module_sp->LoadScriptingResourceInTarget(target, error, 4236 &feedback_stream); 4237 if (error.Fail() && error.AsCString()) 4238 result.AppendWarningWithFormat( 4239 "unable to load scripting data for module %s - error " 4240 "reported was %s", 4241 module_sp->GetFileSpec() 4242 .GetFileNameStrippingExtension() 4243 .GetCString(), 4244 error.AsCString()); 4245 else if (feedback_stream.GetSize()) 4246 result.AppendWarningWithFormat("%s", feedback_stream.GetData()); 4247 4248 flush = true; 4249 result.SetStatus(eReturnStatusSuccessFinishResult); 4250 return true; 4251 } 4252 } 4253 } 4254 // Clear the symbol file spec if anything went wrong 4255 module_sp->SetSymbolFileFileSpec(FileSpec()); 4256 } 4257 4258 namespace fs = llvm::sys::fs; 4259 if (module_spec.GetUUID().IsValid()) { 4260 StreamString ss_symfile_uuid; 4261 module_spec.GetUUID().Dump(&ss_symfile_uuid); 4262 result.AppendErrorWithFormat( 4263 "symbol file '%s' (%s) does not match any existing module%s\n", 4264 symfile_path, ss_symfile_uuid.GetData(), 4265 !fs::is_regular_file(symbol_fspec.GetPath()) 4266 ? "\n please specify the full path to the symbol file" 4267 : ""); 4268 } else { 4269 result.AppendErrorWithFormat( 4270 "symbol file '%s' does not match any existing module%s\n", 4271 symfile_path, 4272 !fs::is_regular_file(symbol_fspec.GetPath()) 4273 ? "\n please specify the full path to the symbol file" 4274 : ""); 4275 } 4276 } else { 4277 result.AppendError( 4278 "one or more executable image paths must be specified"); 4279 } 4280 result.SetStatus(eReturnStatusFailed); 4281 return false; 4282 } 4283 4284 bool DoExecute(Args &args, CommandReturnObject &result) override { 4285 Target *target = m_exe_ctx.GetTargetPtr(); 4286 result.SetStatus(eReturnStatusFailed); 4287 bool flush = false; 4288 ModuleSpec module_spec; 4289 const bool uuid_option_set = 4290 m_uuid_option_group.GetOptionValue().OptionWasSet(); 4291 const bool file_option_set = m_file_option.GetOptionValue().OptionWasSet(); 4292 const bool frame_option_set = 4293 m_current_frame_option.GetOptionValue().OptionWasSet(); 4294 const size_t argc = args.GetArgumentCount(); 4295 4296 if (argc == 0) { 4297 if (uuid_option_set || file_option_set || frame_option_set) { 4298 bool success = false; 4299 bool error_set = false; 4300 if (frame_option_set) { 4301 Process *process = m_exe_ctx.GetProcessPtr(); 4302 if (process) { 4303 const StateType process_state = process->GetState(); 4304 if (StateIsStoppedState(process_state, true)) { 4305 StackFrame *frame = m_exe_ctx.GetFramePtr(); 4306 if (frame) { 4307 ModuleSP frame_module_sp( 4308 frame->GetSymbolContext(eSymbolContextModule).module_sp); 4309 if (frame_module_sp) { 4310 if (FileSystem::Instance().Exists( 4311 frame_module_sp->GetPlatformFileSpec())) { 4312 module_spec.GetArchitecture() = 4313 frame_module_sp->GetArchitecture(); 4314 module_spec.GetFileSpec() = 4315 frame_module_sp->GetPlatformFileSpec(); 4316 } 4317 module_spec.GetUUID() = frame_module_sp->GetUUID(); 4318 success = module_spec.GetUUID().IsValid() || 4319 module_spec.GetFileSpec(); 4320 } else { 4321 result.AppendError("frame has no module"); 4322 error_set = true; 4323 } 4324 } else { 4325 result.AppendError("invalid current frame"); 4326 error_set = true; 4327 } 4328 } else { 4329 result.AppendErrorWithFormat("process is not stopped: %s", 4330 StateAsCString(process_state)); 4331 error_set = true; 4332 } 4333 } else { 4334 result.AppendError( 4335 "a process must exist in order to use the --frame option"); 4336 error_set = true; 4337 } 4338 } else { 4339 if (uuid_option_set) { 4340 module_spec.GetUUID() = 4341 m_uuid_option_group.GetOptionValue().GetCurrentValue(); 4342 success |= module_spec.GetUUID().IsValid(); 4343 } else if (file_option_set) { 4344 module_spec.GetFileSpec() = 4345 m_file_option.GetOptionValue().GetCurrentValue(); 4346 ModuleSP module_sp( 4347 target->GetImages().FindFirstModule(module_spec)); 4348 if (module_sp) { 4349 module_spec.GetFileSpec() = module_sp->GetFileSpec(); 4350 module_spec.GetPlatformFileSpec() = 4351 module_sp->GetPlatformFileSpec(); 4352 module_spec.GetUUID() = module_sp->GetUUID(); 4353 module_spec.GetArchitecture() = module_sp->GetArchitecture(); 4354 } else { 4355 module_spec.GetArchitecture() = target->GetArchitecture(); 4356 } 4357 success |= module_spec.GetUUID().IsValid() || 4358 FileSystem::Instance().Exists(module_spec.GetFileSpec()); 4359 } 4360 } 4361 4362 if (success) { 4363 if (Symbols::DownloadObjectAndSymbolFile(module_spec)) { 4364 if (module_spec.GetSymbolFileSpec()) 4365 success = AddModuleSymbols(target, module_spec, flush, result); 4366 } 4367 } 4368 4369 if (!success && !error_set) { 4370 StreamString error_strm; 4371 if (uuid_option_set) { 4372 error_strm.PutCString("unable to find debug symbols for UUID "); 4373 module_spec.GetUUID().Dump(&error_strm); 4374 } else if (file_option_set) { 4375 error_strm.PutCString( 4376 "unable to find debug symbols for the executable file "); 4377 error_strm << module_spec.GetFileSpec(); 4378 } else if (frame_option_set) { 4379 error_strm.PutCString( 4380 "unable to find debug symbols for the current frame"); 4381 } 4382 result.AppendError(error_strm.GetString()); 4383 } 4384 } else { 4385 result.AppendError("one or more symbol file paths must be specified, " 4386 "or options must be specified"); 4387 } 4388 } else { 4389 if (uuid_option_set) { 4390 result.AppendError("specify either one or more paths to symbol files " 4391 "or use the --uuid option without arguments"); 4392 } else if (frame_option_set) { 4393 result.AppendError("specify either one or more paths to symbol files " 4394 "or use the --frame option without arguments"); 4395 } else if (file_option_set && argc > 1) { 4396 result.AppendError("specify at most one symbol file path when " 4397 "--shlib option is set"); 4398 } else { 4399 PlatformSP platform_sp(target->GetPlatform()); 4400 4401 for (auto &entry : args.entries()) { 4402 if (!entry.ref.empty()) { 4403 auto &symbol_file_spec = module_spec.GetSymbolFileSpec(); 4404 symbol_file_spec.SetFile(entry.ref, FileSpec::Style::native); 4405 FileSystem::Instance().Resolve(symbol_file_spec); 4406 if (file_option_set) { 4407 module_spec.GetFileSpec() = 4408 m_file_option.GetOptionValue().GetCurrentValue(); 4409 } 4410 if (platform_sp) { 4411 FileSpec symfile_spec; 4412 if (platform_sp 4413 ->ResolveSymbolFile(*target, module_spec, symfile_spec) 4414 .Success()) 4415 module_spec.GetSymbolFileSpec() = symfile_spec; 4416 } 4417 4418 ArchSpec arch; 4419 bool symfile_exists = 4420 FileSystem::Instance().Exists(module_spec.GetSymbolFileSpec()); 4421 4422 if (symfile_exists) { 4423 if (!AddModuleSymbols(target, module_spec, flush, result)) 4424 break; 4425 } else { 4426 std::string resolved_symfile_path = 4427 module_spec.GetSymbolFileSpec().GetPath(); 4428 if (resolved_symfile_path != entry.ref) { 4429 result.AppendErrorWithFormat( 4430 "invalid module path '%s' with resolved path '%s'\n", 4431 entry.c_str(), resolved_symfile_path.c_str()); 4432 break; 4433 } 4434 result.AppendErrorWithFormat("invalid module path '%s'\n", 4435 entry.c_str()); 4436 break; 4437 } 4438 } 4439 } 4440 } 4441 } 4442 4443 if (flush) { 4444 Process *process = m_exe_ctx.GetProcessPtr(); 4445 if (process) 4446 process->Flush(); 4447 } 4448 return result.Succeeded(); 4449 } 4450 4451 OptionGroupOptions m_option_group; 4452 OptionGroupUUID m_uuid_option_group; 4453 OptionGroupFile m_file_option; 4454 OptionGroupBoolean m_current_frame_option; 4455 }; 4456 4457 #pragma mark CommandObjectTargetSymbols 4458 4459 // CommandObjectTargetSymbols 4460 4461 class CommandObjectTargetSymbols : public CommandObjectMultiword { 4462 public: 4463 // Constructors and Destructors 4464 CommandObjectTargetSymbols(CommandInterpreter &interpreter) 4465 : CommandObjectMultiword( 4466 interpreter, "target symbols", 4467 "Commands for adding and managing debug symbol files.", 4468 "target symbols <sub-command> ...") { 4469 LoadSubCommand( 4470 "add", CommandObjectSP(new CommandObjectTargetSymbolsAdd(interpreter))); 4471 } 4472 4473 ~CommandObjectTargetSymbols() override = default; 4474 4475 private: 4476 // For CommandObjectTargetModules only 4477 DISALLOW_COPY_AND_ASSIGN(CommandObjectTargetSymbols); 4478 }; 4479 4480 #pragma mark CommandObjectTargetStopHookAdd 4481 4482 // CommandObjectTargetStopHookAdd 4483 #define LLDB_OPTIONS_target_stop_hook_add 4484 #include "CommandOptions.inc" 4485 4486 class CommandObjectTargetStopHookAdd : public CommandObjectParsed, 4487 public IOHandlerDelegateMultiline { 4488 public: 4489 class CommandOptions : public Options { 4490 public: 4491 CommandOptions() 4492 : Options(), m_line_start(0), m_line_end(UINT_MAX), 4493 m_func_name_type_mask(eFunctionNameTypeAuto), 4494 m_sym_ctx_specified(false), m_thread_specified(false), 4495 m_use_one_liner(false), m_one_liner() {} 4496 4497 ~CommandOptions() override = default; 4498 4499 llvm::ArrayRef<OptionDefinition> GetDefinitions() override { 4500 return llvm::makeArrayRef(g_target_stop_hook_add_options); 4501 } 4502 4503 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, 4504 ExecutionContext *execution_context) override { 4505 Status error; 4506 const int short_option = m_getopt_table[option_idx].val; 4507 4508 switch (short_option) { 4509 case 'c': 4510 m_class_name = option_arg; 4511 m_sym_ctx_specified = true; 4512 break; 4513 4514 case 'e': 4515 if (option_arg.getAsInteger(0, m_line_end)) { 4516 error.SetErrorStringWithFormat("invalid end line number: \"%s\"", 4517 option_arg.str().c_str()); 4518 break; 4519 } 4520 m_sym_ctx_specified = true; 4521 break; 4522 4523 case 'G': { 4524 bool value, success; 4525 value = OptionArgParser::ToBoolean(option_arg, false, &success); 4526 if (success) { 4527 m_auto_continue = value; 4528 } else 4529 error.SetErrorStringWithFormat( 4530 "invalid boolean value '%s' passed for -G option", 4531 option_arg.str().c_str()); 4532 } 4533 break; 4534 case 'l': 4535 if (option_arg.getAsInteger(0, m_line_start)) { 4536 error.SetErrorStringWithFormat("invalid start line number: \"%s\"", 4537 option_arg.str().c_str()); 4538 break; 4539 } 4540 m_sym_ctx_specified = true; 4541 break; 4542 4543 case 'i': 4544 m_no_inlines = true; 4545 break; 4546 4547 case 'n': 4548 m_function_name = option_arg; 4549 m_func_name_type_mask |= eFunctionNameTypeAuto; 4550 m_sym_ctx_specified = true; 4551 break; 4552 4553 case 'f': 4554 m_file_name = option_arg; 4555 m_sym_ctx_specified = true; 4556 break; 4557 4558 case 's': 4559 m_module_name = option_arg; 4560 m_sym_ctx_specified = true; 4561 break; 4562 4563 case 't': 4564 if (option_arg.getAsInteger(0, m_thread_id)) 4565 error.SetErrorStringWithFormat("invalid thread id string '%s'", 4566 option_arg.str().c_str()); 4567 m_thread_specified = true; 4568 break; 4569 4570 case 'T': 4571 m_thread_name = option_arg; 4572 m_thread_specified = true; 4573 break; 4574 4575 case 'q': 4576 m_queue_name = option_arg; 4577 m_thread_specified = true; 4578 break; 4579 4580 case 'x': 4581 if (option_arg.getAsInteger(0, m_thread_index)) 4582 error.SetErrorStringWithFormat("invalid thread index string '%s'", 4583 option_arg.str().c_str()); 4584 m_thread_specified = true; 4585 break; 4586 4587 case 'o': 4588 m_use_one_liner = true; 4589 m_one_liner.push_back(option_arg); 4590 break; 4591 4592 default: 4593 error.SetErrorStringWithFormat("unrecognized option %c.", short_option); 4594 break; 4595 } 4596 return error; 4597 } 4598 4599 void OptionParsingStarting(ExecutionContext *execution_context) override { 4600 m_class_name.clear(); 4601 m_function_name.clear(); 4602 m_line_start = 0; 4603 m_line_end = UINT_MAX; 4604 m_file_name.clear(); 4605 m_module_name.clear(); 4606 m_func_name_type_mask = eFunctionNameTypeAuto; 4607 m_thread_id = LLDB_INVALID_THREAD_ID; 4608 m_thread_index = UINT32_MAX; 4609 m_thread_name.clear(); 4610 m_queue_name.clear(); 4611 4612 m_no_inlines = false; 4613 m_sym_ctx_specified = false; 4614 m_thread_specified = false; 4615 4616 m_use_one_liner = false; 4617 m_one_liner.clear(); 4618 m_auto_continue = false; 4619 } 4620 4621 std::string m_class_name; 4622 std::string m_function_name; 4623 uint32_t m_line_start; 4624 uint32_t m_line_end; 4625 std::string m_file_name; 4626 std::string m_module_name; 4627 uint32_t m_func_name_type_mask; // A pick from lldb::FunctionNameType. 4628 lldb::tid_t m_thread_id; 4629 uint32_t m_thread_index; 4630 std::string m_thread_name; 4631 std::string m_queue_name; 4632 bool m_sym_ctx_specified; 4633 bool m_no_inlines; 4634 bool m_thread_specified; 4635 // Instance variables to hold the values for one_liner options. 4636 bool m_use_one_liner; 4637 std::vector<std::string> m_one_liner; 4638 bool m_auto_continue; 4639 }; 4640 4641 CommandObjectTargetStopHookAdd(CommandInterpreter &interpreter) 4642 : CommandObjectParsed(interpreter, "target stop-hook add", 4643 "Add a hook to be executed when the target stops.", 4644 "target stop-hook add"), 4645 IOHandlerDelegateMultiline("DONE", 4646 IOHandlerDelegate::Completion::LLDBCommand), 4647 m_options() {} 4648 4649 ~CommandObjectTargetStopHookAdd() override = default; 4650 4651 Options *GetOptions() override { return &m_options; } 4652 4653 protected: 4654 void IOHandlerActivated(IOHandler &io_handler, bool interactive) override { 4655 StreamFileSP output_sp(io_handler.GetOutputStreamFile()); 4656 if (output_sp && interactive) { 4657 output_sp->PutCString( 4658 "Enter your stop hook command(s). Type 'DONE' to end.\n"); 4659 output_sp->Flush(); 4660 } 4661 } 4662 4663 void IOHandlerInputComplete(IOHandler &io_handler, 4664 std::string &line) override { 4665 if (m_stop_hook_sp) { 4666 if (line.empty()) { 4667 StreamFileSP error_sp(io_handler.GetErrorStreamFile()); 4668 if (error_sp) { 4669 error_sp->Printf("error: stop hook #%" PRIu64 4670 " aborted, no commands.\n", 4671 m_stop_hook_sp->GetID()); 4672 error_sp->Flush(); 4673 } 4674 Target *target = GetDebugger().GetSelectedTarget().get(); 4675 if (target) 4676 target->RemoveStopHookByID(m_stop_hook_sp->GetID()); 4677 } else { 4678 m_stop_hook_sp->GetCommandPointer()->SplitIntoLines(line); 4679 StreamFileSP output_sp(io_handler.GetOutputStreamFile()); 4680 if (output_sp) { 4681 output_sp->Printf("Stop hook #%" PRIu64 " added.\n", 4682 m_stop_hook_sp->GetID()); 4683 output_sp->Flush(); 4684 } 4685 } 4686 m_stop_hook_sp.reset(); 4687 } 4688 io_handler.SetIsDone(true); 4689 } 4690 4691 bool DoExecute(Args &command, CommandReturnObject &result) override { 4692 m_stop_hook_sp.reset(); 4693 4694 Target *target = GetSelectedOrDummyTarget(); 4695 if (target) { 4696 Target::StopHookSP new_hook_sp = target->CreateStopHook(); 4697 4698 // First step, make the specifier. 4699 std::unique_ptr<SymbolContextSpecifier> specifier_up; 4700 if (m_options.m_sym_ctx_specified) { 4701 specifier_up.reset( 4702 new SymbolContextSpecifier(GetDebugger().GetSelectedTarget())); 4703 4704 if (!m_options.m_module_name.empty()) { 4705 specifier_up->AddSpecification( 4706 m_options.m_module_name.c_str(), 4707 SymbolContextSpecifier::eModuleSpecified); 4708 } 4709 4710 if (!m_options.m_class_name.empty()) { 4711 specifier_up->AddSpecification( 4712 m_options.m_class_name.c_str(), 4713 SymbolContextSpecifier::eClassOrNamespaceSpecified); 4714 } 4715 4716 if (!m_options.m_file_name.empty()) { 4717 specifier_up->AddSpecification( 4718 m_options.m_file_name.c_str(), 4719 SymbolContextSpecifier::eFileSpecified); 4720 } 4721 4722 if (m_options.m_line_start != 0) { 4723 specifier_up->AddLineSpecification( 4724 m_options.m_line_start, 4725 SymbolContextSpecifier::eLineStartSpecified); 4726 } 4727 4728 if (m_options.m_line_end != UINT_MAX) { 4729 specifier_up->AddLineSpecification( 4730 m_options.m_line_end, SymbolContextSpecifier::eLineEndSpecified); 4731 } 4732 4733 if (!m_options.m_function_name.empty()) { 4734 specifier_up->AddSpecification( 4735 m_options.m_function_name.c_str(), 4736 SymbolContextSpecifier::eFunctionSpecified); 4737 } 4738 } 4739 4740 if (specifier_up) 4741 new_hook_sp->SetSpecifier(specifier_up.release()); 4742 4743 // Next see if any of the thread options have been entered: 4744 4745 if (m_options.m_thread_specified) { 4746 ThreadSpec *thread_spec = new ThreadSpec(); 4747 4748 if (m_options.m_thread_id != LLDB_INVALID_THREAD_ID) { 4749 thread_spec->SetTID(m_options.m_thread_id); 4750 } 4751 4752 if (m_options.m_thread_index != UINT32_MAX) 4753 thread_spec->SetIndex(m_options.m_thread_index); 4754 4755 if (!m_options.m_thread_name.empty()) 4756 thread_spec->SetName(m_options.m_thread_name.c_str()); 4757 4758 if (!m_options.m_queue_name.empty()) 4759 thread_spec->SetQueueName(m_options.m_queue_name.c_str()); 4760 4761 new_hook_sp->SetThreadSpecifier(thread_spec); 4762 } 4763 4764 new_hook_sp->SetAutoContinue(m_options.m_auto_continue); 4765 if (m_options.m_use_one_liner) { 4766 // Use one-liners. 4767 for (auto cmd : m_options.m_one_liner) 4768 new_hook_sp->GetCommandPointer()->AppendString( 4769 cmd.c_str()); 4770 result.AppendMessageWithFormat("Stop hook #%" PRIu64 " added.\n", 4771 new_hook_sp->GetID()); 4772 } else { 4773 m_stop_hook_sp = new_hook_sp; 4774 m_interpreter.GetLLDBCommandsFromIOHandler( 4775 "> ", // Prompt 4776 *this, // IOHandlerDelegate 4777 true, // Run IOHandler in async mode 4778 nullptr); // Baton for the "io_handler" that will be passed back 4779 // into our IOHandlerDelegate functions 4780 } 4781 result.SetStatus(eReturnStatusSuccessFinishNoResult); 4782 } else { 4783 result.AppendError("invalid target\n"); 4784 result.SetStatus(eReturnStatusFailed); 4785 } 4786 4787 return result.Succeeded(); 4788 } 4789 4790 private: 4791 CommandOptions m_options; 4792 Target::StopHookSP m_stop_hook_sp; 4793 }; 4794 4795 #pragma mark CommandObjectTargetStopHookDelete 4796 4797 // CommandObjectTargetStopHookDelete 4798 4799 class CommandObjectTargetStopHookDelete : public CommandObjectParsed { 4800 public: 4801 CommandObjectTargetStopHookDelete(CommandInterpreter &interpreter) 4802 : CommandObjectParsed(interpreter, "target stop-hook delete", 4803 "Delete a stop-hook.", 4804 "target stop-hook delete [<idx>]") {} 4805 4806 ~CommandObjectTargetStopHookDelete() override = default; 4807 4808 protected: 4809 bool DoExecute(Args &command, CommandReturnObject &result) override { 4810 Target *target = GetSelectedOrDummyTarget(); 4811 if (target) { 4812 // FIXME: see if we can use the breakpoint id style parser? 4813 size_t num_args = command.GetArgumentCount(); 4814 if (num_args == 0) { 4815 if (!m_interpreter.Confirm("Delete all stop hooks?", true)) { 4816 result.SetStatus(eReturnStatusFailed); 4817 return false; 4818 } else { 4819 target->RemoveAllStopHooks(); 4820 } 4821 } else { 4822 bool success; 4823 for (size_t i = 0; i < num_args; i++) { 4824 lldb::user_id_t user_id = StringConvert::ToUInt32( 4825 command.GetArgumentAtIndex(i), 0, 0, &success); 4826 if (!success) { 4827 result.AppendErrorWithFormat("invalid stop hook id: \"%s\".\n", 4828 command.GetArgumentAtIndex(i)); 4829 result.SetStatus(eReturnStatusFailed); 4830 return false; 4831 } 4832 success = target->RemoveStopHookByID(user_id); 4833 if (!success) { 4834 result.AppendErrorWithFormat("unknown stop hook id: \"%s\".\n", 4835 command.GetArgumentAtIndex(i)); 4836 result.SetStatus(eReturnStatusFailed); 4837 return false; 4838 } 4839 } 4840 } 4841 result.SetStatus(eReturnStatusSuccessFinishNoResult); 4842 } else { 4843 result.AppendError("invalid target\n"); 4844 result.SetStatus(eReturnStatusFailed); 4845 } 4846 4847 return result.Succeeded(); 4848 } 4849 }; 4850 4851 #pragma mark CommandObjectTargetStopHookEnableDisable 4852 4853 // CommandObjectTargetStopHookEnableDisable 4854 4855 class CommandObjectTargetStopHookEnableDisable : public CommandObjectParsed { 4856 public: 4857 CommandObjectTargetStopHookEnableDisable(CommandInterpreter &interpreter, 4858 bool enable, const char *name, 4859 const char *help, const char *syntax) 4860 : CommandObjectParsed(interpreter, name, help, syntax), m_enable(enable) { 4861 } 4862 4863 ~CommandObjectTargetStopHookEnableDisable() override = default; 4864 4865 protected: 4866 bool DoExecute(Args &command, CommandReturnObject &result) override { 4867 Target *target = GetSelectedOrDummyTarget(); 4868 if (target) { 4869 // FIXME: see if we can use the breakpoint id style parser? 4870 size_t num_args = command.GetArgumentCount(); 4871 bool success; 4872 4873 if (num_args == 0) { 4874 target->SetAllStopHooksActiveState(m_enable); 4875 } else { 4876 for (size_t i = 0; i < num_args; i++) { 4877 lldb::user_id_t user_id = StringConvert::ToUInt32( 4878 command.GetArgumentAtIndex(i), 0, 0, &success); 4879 if (!success) { 4880 result.AppendErrorWithFormat("invalid stop hook id: \"%s\".\n", 4881 command.GetArgumentAtIndex(i)); 4882 result.SetStatus(eReturnStatusFailed); 4883 return false; 4884 } 4885 success = target->SetStopHookActiveStateByID(user_id, m_enable); 4886 if (!success) { 4887 result.AppendErrorWithFormat("unknown stop hook id: \"%s\".\n", 4888 command.GetArgumentAtIndex(i)); 4889 result.SetStatus(eReturnStatusFailed); 4890 return false; 4891 } 4892 } 4893 } 4894 result.SetStatus(eReturnStatusSuccessFinishNoResult); 4895 } else { 4896 result.AppendError("invalid target\n"); 4897 result.SetStatus(eReturnStatusFailed); 4898 } 4899 return result.Succeeded(); 4900 } 4901 4902 private: 4903 bool m_enable; 4904 }; 4905 4906 #pragma mark CommandObjectTargetStopHookList 4907 4908 // CommandObjectTargetStopHookList 4909 4910 class CommandObjectTargetStopHookList : public CommandObjectParsed { 4911 public: 4912 CommandObjectTargetStopHookList(CommandInterpreter &interpreter) 4913 : CommandObjectParsed(interpreter, "target stop-hook list", 4914 "List all stop-hooks.", 4915 "target stop-hook list [<type>]") {} 4916 4917 ~CommandObjectTargetStopHookList() override = default; 4918 4919 protected: 4920 bool DoExecute(Args &command, CommandReturnObject &result) override { 4921 Target *target = GetSelectedOrDummyTarget(); 4922 if (!target) { 4923 result.AppendError("invalid target\n"); 4924 result.SetStatus(eReturnStatusFailed); 4925 return result.Succeeded(); 4926 } 4927 4928 size_t num_hooks = target->GetNumStopHooks(); 4929 if (num_hooks == 0) { 4930 result.GetOutputStream().PutCString("No stop hooks.\n"); 4931 } else { 4932 for (size_t i = 0; i < num_hooks; i++) { 4933 Target::StopHookSP this_hook = target->GetStopHookAtIndex(i); 4934 if (i > 0) 4935 result.GetOutputStream().PutCString("\n"); 4936 this_hook->GetDescription(&(result.GetOutputStream()), 4937 eDescriptionLevelFull); 4938 } 4939 } 4940 result.SetStatus(eReturnStatusSuccessFinishResult); 4941 return result.Succeeded(); 4942 } 4943 }; 4944 4945 #pragma mark CommandObjectMultiwordTargetStopHooks 4946 4947 // CommandObjectMultiwordTargetStopHooks 4948 4949 class CommandObjectMultiwordTargetStopHooks : public CommandObjectMultiword { 4950 public: 4951 CommandObjectMultiwordTargetStopHooks(CommandInterpreter &interpreter) 4952 : CommandObjectMultiword( 4953 interpreter, "target stop-hook", 4954 "Commands for operating on debugger target stop-hooks.", 4955 "target stop-hook <subcommand> [<subcommand-options>]") { 4956 LoadSubCommand("add", CommandObjectSP( 4957 new CommandObjectTargetStopHookAdd(interpreter))); 4958 LoadSubCommand( 4959 "delete", 4960 CommandObjectSP(new CommandObjectTargetStopHookDelete(interpreter))); 4961 LoadSubCommand("disable", 4962 CommandObjectSP(new CommandObjectTargetStopHookEnableDisable( 4963 interpreter, false, "target stop-hook disable [<id>]", 4964 "Disable a stop-hook.", "target stop-hook disable"))); 4965 LoadSubCommand("enable", 4966 CommandObjectSP(new CommandObjectTargetStopHookEnableDisable( 4967 interpreter, true, "target stop-hook enable [<id>]", 4968 "Enable a stop-hook.", "target stop-hook enable"))); 4969 LoadSubCommand("list", CommandObjectSP(new CommandObjectTargetStopHookList( 4970 interpreter))); 4971 } 4972 4973 ~CommandObjectMultiwordTargetStopHooks() override = default; 4974 }; 4975 4976 #pragma mark CommandObjectMultiwordTarget 4977 4978 // CommandObjectMultiwordTarget 4979 4980 CommandObjectMultiwordTarget::CommandObjectMultiwordTarget( 4981 CommandInterpreter &interpreter) 4982 : CommandObjectMultiword(interpreter, "target", 4983 "Commands for operating on debugger targets.", 4984 "target <subcommand> [<subcommand-options>]") { 4985 LoadSubCommand("create", 4986 CommandObjectSP(new CommandObjectTargetCreate(interpreter))); 4987 LoadSubCommand("delete", 4988 CommandObjectSP(new CommandObjectTargetDelete(interpreter))); 4989 LoadSubCommand("list", 4990 CommandObjectSP(new CommandObjectTargetList(interpreter))); 4991 LoadSubCommand("select", 4992 CommandObjectSP(new CommandObjectTargetSelect(interpreter))); 4993 LoadSubCommand( 4994 "stop-hook", 4995 CommandObjectSP(new CommandObjectMultiwordTargetStopHooks(interpreter))); 4996 LoadSubCommand("modules", 4997 CommandObjectSP(new CommandObjectTargetModules(interpreter))); 4998 LoadSubCommand("symbols", 4999 CommandObjectSP(new CommandObjectTargetSymbols(interpreter))); 5000 LoadSubCommand("variable", 5001 CommandObjectSP(new CommandObjectTargetVariable(interpreter))); 5002 } 5003 5004 CommandObjectMultiwordTarget::~CommandObjectMultiwordTarget() = default; 5005