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