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