1 //===-- Target.cpp --------------------------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "lldb/Target/Target.h" 10 #include "lldb/Breakpoint/BreakpointIDList.h" 11 #include "lldb/Breakpoint/BreakpointPrecondition.h" 12 #include "lldb/Breakpoint/BreakpointResolver.h" 13 #include "lldb/Breakpoint/BreakpointResolverAddress.h" 14 #include "lldb/Breakpoint/BreakpointResolverFileLine.h" 15 #include "lldb/Breakpoint/BreakpointResolverFileRegex.h" 16 #include "lldb/Breakpoint/BreakpointResolverName.h" 17 #include "lldb/Breakpoint/BreakpointResolverScripted.h" 18 #include "lldb/Breakpoint/Watchpoint.h" 19 #include "lldb/Core/Debugger.h" 20 #include "lldb/Core/Module.h" 21 #include "lldb/Core/ModuleSpec.h" 22 #include "lldb/Core/PluginManager.h" 23 #include "lldb/Core/SearchFilter.h" 24 #include "lldb/Core/Section.h" 25 #include "lldb/Core/SourceManager.h" 26 #include "lldb/Core/StructuredDataImpl.h" 27 #include "lldb/DataFormatters/FormatterSection.h" 28 #include "lldb/Expression/DiagnosticManager.h" 29 #include "lldb/Expression/ExpressionVariable.h" 30 #include "lldb/Expression/REPL.h" 31 #include "lldb/Expression/UserExpression.h" 32 #include "lldb/Expression/UtilityFunction.h" 33 #include "lldb/Host/Host.h" 34 #include "lldb/Host/PosixApi.h" 35 #include "lldb/Host/StreamFile.h" 36 #include "lldb/Interpreter/CommandInterpreter.h" 37 #include "lldb/Interpreter/CommandReturnObject.h" 38 #include "lldb/Interpreter/Interfaces/ScriptedStopHookInterface.h" 39 #include "lldb/Interpreter/OptionGroupWatchpoint.h" 40 #include "lldb/Interpreter/OptionValues.h" 41 #include "lldb/Interpreter/Property.h" 42 #include "lldb/Symbol/Function.h" 43 #include "lldb/Symbol/ObjectFile.h" 44 #include "lldb/Symbol/Symbol.h" 45 #include "lldb/Target/ABI.h" 46 #include "lldb/Target/ExecutionContext.h" 47 #include "lldb/Target/Language.h" 48 #include "lldb/Target/LanguageRuntime.h" 49 #include "lldb/Target/Process.h" 50 #include "lldb/Target/RegisterTypeBuilder.h" 51 #include "lldb/Target/SectionLoadList.h" 52 #include "lldb/Target/StackFrame.h" 53 #include "lldb/Target/StackFrameRecognizer.h" 54 #include "lldb/Target/SystemRuntime.h" 55 #include "lldb/Target/Thread.h" 56 #include "lldb/Target/ThreadSpec.h" 57 #include "lldb/Target/UnixSignals.h" 58 #include "lldb/Utility/Event.h" 59 #include "lldb/Utility/FileSpec.h" 60 #include "lldb/Utility/LLDBAssert.h" 61 #include "lldb/Utility/LLDBLog.h" 62 #include "lldb/Utility/Log.h" 63 #include "lldb/Utility/RealpathPrefixes.h" 64 #include "lldb/Utility/State.h" 65 #include "lldb/Utility/StreamString.h" 66 #include "lldb/Utility/Timer.h" 67 68 #include "llvm/ADT/ScopeExit.h" 69 #include "llvm/ADT/SetVector.h" 70 #include "llvm/Support/ThreadPool.h" 71 72 #include <memory> 73 #include <mutex> 74 #include <optional> 75 #include <sstream> 76 77 using namespace lldb; 78 using namespace lldb_private; 79 80 namespace { 81 82 struct ExecutableInstaller { 83 84 ExecutableInstaller(PlatformSP platform, ModuleSP module) 85 : m_platform{platform}, m_module{module}, 86 m_local_file{m_module->GetFileSpec()}, 87 m_remote_file{m_module->GetRemoteInstallFileSpec()} {} 88 89 void setupRemoteFile() const { m_module->SetPlatformFileSpec(m_remote_file); } 90 91 PlatformSP m_platform; 92 ModuleSP m_module; 93 const FileSpec m_local_file; 94 const FileSpec m_remote_file; 95 }; 96 97 struct MainExecutableInstaller { 98 99 MainExecutableInstaller(PlatformSP platform, ModuleSP module, TargetSP target, 100 ProcessLaunchInfo &launch_info) 101 : m_platform{platform}, m_module{module}, 102 m_local_file{m_module->GetFileSpec()}, 103 m_remote_file{ 104 getRemoteFileSpec(m_platform, target, m_module, m_local_file)}, 105 m_launch_info{launch_info} {} 106 107 void setupRemoteFile() const { 108 m_module->SetPlatformFileSpec(m_remote_file); 109 m_launch_info.SetExecutableFile(m_remote_file, 110 /*add_exe_file_as_first_arg=*/false); 111 m_platform->SetFilePermissions(m_remote_file, 0700 /*-rwx------*/); 112 } 113 114 PlatformSP m_platform; 115 ModuleSP m_module; 116 const FileSpec m_local_file; 117 const FileSpec m_remote_file; 118 119 private: 120 static FileSpec getRemoteFileSpec(PlatformSP platform, TargetSP target, 121 ModuleSP module, 122 const FileSpec &local_file) { 123 FileSpec remote_file = module->GetRemoteInstallFileSpec(); 124 if (remote_file || !target->GetAutoInstallMainExecutable()) 125 return remote_file; 126 127 if (!local_file) 128 return {}; 129 130 remote_file = platform->GetRemoteWorkingDirectory(); 131 remote_file.AppendPathComponent(local_file.GetFilename().GetCString()); 132 133 return remote_file; 134 } 135 136 ProcessLaunchInfo &m_launch_info; 137 }; 138 } // namespace 139 140 template <typename Installer> 141 static Status installExecutable(const Installer &installer) { 142 if (!installer.m_local_file || !installer.m_remote_file) 143 return Status(); 144 145 Status error = installer.m_platform->Install(installer.m_local_file, 146 installer.m_remote_file); 147 if (error.Fail()) 148 return error; 149 150 installer.setupRemoteFile(); 151 return Status(); 152 } 153 154 constexpr std::chrono::milliseconds EvaluateExpressionOptions::default_timeout; 155 156 Target::Arch::Arch(const ArchSpec &spec) 157 : m_spec(spec), 158 m_plugin_up(PluginManager::CreateArchitectureInstance(spec)) {} 159 160 const Target::Arch &Target::Arch::operator=(const ArchSpec &spec) { 161 m_spec = spec; 162 m_plugin_up = PluginManager::CreateArchitectureInstance(spec); 163 return *this; 164 } 165 166 llvm::StringRef Target::GetStaticBroadcasterClass() { 167 static constexpr llvm::StringLiteral class_name("lldb.target"); 168 return class_name; 169 } 170 171 Target::Target(Debugger &debugger, const ArchSpec &target_arch, 172 const lldb::PlatformSP &platform_sp, bool is_dummy_target) 173 : TargetProperties(this), 174 Broadcaster(debugger.GetBroadcasterManager(), 175 Target::GetStaticBroadcasterClass().str()), 176 ExecutionContextScope(), m_debugger(debugger), m_platform_sp(platform_sp), 177 m_mutex(), m_arch(target_arch), m_images(this), m_section_load_history(), 178 m_breakpoint_list(false), m_internal_breakpoint_list(true), 179 m_watchpoint_list(), m_process_sp(), m_search_filter_sp(), 180 m_image_search_paths(ImageSearchPathsChanged, this), 181 m_source_manager_up(), m_stop_hooks(), m_stop_hook_next_id(0), 182 m_latest_stop_hook_id(0), m_valid(true), m_suppress_stop_hooks(false), 183 m_is_dummy_target(is_dummy_target), 184 m_frame_recognizer_manager_up( 185 std::make_unique<StackFrameRecognizerManager>()) { 186 SetEventName(eBroadcastBitBreakpointChanged, "breakpoint-changed"); 187 SetEventName(eBroadcastBitModulesLoaded, "modules-loaded"); 188 SetEventName(eBroadcastBitModulesUnloaded, "modules-unloaded"); 189 SetEventName(eBroadcastBitWatchpointChanged, "watchpoint-changed"); 190 SetEventName(eBroadcastBitSymbolsLoaded, "symbols-loaded"); 191 192 CheckInWithManager(); 193 194 LLDB_LOG(GetLog(LLDBLog::Object), "{0} Target::Target()", 195 static_cast<void *>(this)); 196 if (target_arch.IsValid()) { 197 LLDB_LOG(GetLog(LLDBLog::Target), 198 "Target::Target created with architecture {0} ({1})", 199 target_arch.GetArchitectureName(), 200 target_arch.GetTriple().getTriple().c_str()); 201 } 202 203 UpdateLaunchInfoFromProperties(); 204 } 205 206 Target::~Target() { 207 Log *log = GetLog(LLDBLog::Object); 208 LLDB_LOG(log, "{0} Target::~Target()", static_cast<void *>(this)); 209 DeleteCurrentProcess(); 210 } 211 212 void Target::PrimeFromDummyTarget(Target &target) { 213 m_stop_hooks = target.m_stop_hooks; 214 215 for (const auto &breakpoint_sp : target.m_breakpoint_list.Breakpoints()) { 216 if (breakpoint_sp->IsInternal()) 217 continue; 218 219 BreakpointSP new_bp( 220 Breakpoint::CopyFromBreakpoint(shared_from_this(), *breakpoint_sp)); 221 AddBreakpoint(std::move(new_bp), false); 222 } 223 224 for (const auto &bp_name_entry : target.m_breakpoint_names) { 225 AddBreakpointName(std::make_unique<BreakpointName>(*bp_name_entry.second)); 226 } 227 228 m_frame_recognizer_manager_up = std::make_unique<StackFrameRecognizerManager>( 229 *target.m_frame_recognizer_manager_up); 230 231 m_dummy_signals = target.m_dummy_signals; 232 } 233 234 void Target::Dump(Stream *s, lldb::DescriptionLevel description_level) { 235 // s->Printf("%.*p: ", (int)sizeof(void*) * 2, this); 236 if (description_level != lldb::eDescriptionLevelBrief) { 237 s->Indent(); 238 s->PutCString("Target\n"); 239 s->IndentMore(); 240 m_images.Dump(s); 241 m_breakpoint_list.Dump(s); 242 m_internal_breakpoint_list.Dump(s); 243 s->IndentLess(); 244 } else { 245 Module *exe_module = GetExecutableModulePointer(); 246 if (exe_module) 247 s->PutCString(exe_module->GetFileSpec().GetFilename().GetCString()); 248 else 249 s->PutCString("No executable module."); 250 } 251 } 252 253 void Target::CleanupProcess() { 254 // Do any cleanup of the target we need to do between process instances. 255 // NB It is better to do this before destroying the process in case the 256 // clean up needs some help from the process. 257 m_breakpoint_list.ClearAllBreakpointSites(); 258 m_internal_breakpoint_list.ClearAllBreakpointSites(); 259 ResetBreakpointHitCounts(); 260 // Disable watchpoints just on the debugger side. 261 std::unique_lock<std::recursive_mutex> lock; 262 this->GetWatchpointList().GetListMutex(lock); 263 DisableAllWatchpoints(false); 264 ClearAllWatchpointHitCounts(); 265 ClearAllWatchpointHistoricValues(); 266 m_latest_stop_hook_id = 0; 267 } 268 269 void Target::DeleteCurrentProcess() { 270 if (m_process_sp) { 271 // We dispose any active tracing sessions on the current process 272 m_trace_sp.reset(); 273 274 if (m_process_sp->IsAlive()) 275 m_process_sp->Destroy(false); 276 277 m_process_sp->Finalize(false /* not destructing */); 278 279 // Let the process finalize itself first, then clear the section load 280 // history. Some objects owned by the process might end up calling 281 // SectionLoadHistory::SetSectionUnloaded() which can create entries in 282 // the section load history that can mess up subsequent processes. 283 m_section_load_history.Clear(); 284 285 CleanupProcess(); 286 287 m_process_sp.reset(); 288 } 289 } 290 291 const lldb::ProcessSP &Target::CreateProcess(ListenerSP listener_sp, 292 llvm::StringRef plugin_name, 293 const FileSpec *crash_file, 294 bool can_connect) { 295 if (!listener_sp) 296 listener_sp = GetDebugger().GetListener(); 297 DeleteCurrentProcess(); 298 m_process_sp = Process::FindPlugin(shared_from_this(), plugin_name, 299 listener_sp, crash_file, can_connect); 300 return m_process_sp; 301 } 302 303 const lldb::ProcessSP &Target::GetProcessSP() const { return m_process_sp; } 304 305 lldb::REPLSP Target::GetREPL(Status &err, lldb::LanguageType language, 306 const char *repl_options, bool can_create) { 307 if (language == eLanguageTypeUnknown) 308 language = m_debugger.GetREPLLanguage(); 309 310 if (language == eLanguageTypeUnknown) { 311 LanguageSet repl_languages = Language::GetLanguagesSupportingREPLs(); 312 313 if (auto single_lang = repl_languages.GetSingularLanguage()) { 314 language = *single_lang; 315 } else if (repl_languages.Empty()) { 316 err = Status::FromErrorString( 317 "LLDB isn't configured with REPL support for any languages."); 318 return REPLSP(); 319 } else { 320 err = Status::FromErrorString( 321 "Multiple possible REPL languages. Please specify a language."); 322 return REPLSP(); 323 } 324 } 325 326 REPLMap::iterator pos = m_repl_map.find(language); 327 328 if (pos != m_repl_map.end()) { 329 return pos->second; 330 } 331 332 if (!can_create) { 333 err = Status::FromErrorStringWithFormat( 334 "Couldn't find an existing REPL for %s, and can't create a new one", 335 Language::GetNameForLanguageType(language)); 336 return lldb::REPLSP(); 337 } 338 339 Debugger *const debugger = nullptr; 340 lldb::REPLSP ret = REPL::Create(err, language, debugger, this, repl_options); 341 342 if (ret) { 343 m_repl_map[language] = ret; 344 return m_repl_map[language]; 345 } 346 347 if (err.Success()) { 348 err = Status::FromErrorStringWithFormat( 349 "Couldn't create a REPL for %s", 350 Language::GetNameForLanguageType(language)); 351 } 352 353 return lldb::REPLSP(); 354 } 355 356 void Target::SetREPL(lldb::LanguageType language, lldb::REPLSP repl_sp) { 357 lldbassert(!m_repl_map.count(language)); 358 359 m_repl_map[language] = repl_sp; 360 } 361 362 void Target::Destroy() { 363 std::lock_guard<std::recursive_mutex> guard(m_mutex); 364 m_valid = false; 365 DeleteCurrentProcess(); 366 m_platform_sp.reset(); 367 m_arch = ArchSpec(); 368 ClearModules(true); 369 m_section_load_history.Clear(); 370 const bool notify = false; 371 m_breakpoint_list.RemoveAll(notify); 372 m_internal_breakpoint_list.RemoveAll(notify); 373 m_last_created_breakpoint.reset(); 374 m_watchpoint_list.RemoveAll(notify); 375 m_last_created_watchpoint.reset(); 376 m_search_filter_sp.reset(); 377 m_image_search_paths.Clear(notify); 378 m_stop_hooks.clear(); 379 m_stop_hook_next_id = 0; 380 m_suppress_stop_hooks = false; 381 m_repl_map.clear(); 382 Args signal_args; 383 ClearDummySignals(signal_args); 384 } 385 386 llvm::StringRef Target::GetABIName() const { 387 lldb::ABISP abi_sp; 388 if (m_process_sp) 389 abi_sp = m_process_sp->GetABI(); 390 if (!abi_sp) 391 abi_sp = ABI::FindPlugin(ProcessSP(), GetArchitecture()); 392 if (abi_sp) 393 return abi_sp->GetPluginName(); 394 return {}; 395 } 396 397 BreakpointList &Target::GetBreakpointList(bool internal) { 398 if (internal) 399 return m_internal_breakpoint_list; 400 else 401 return m_breakpoint_list; 402 } 403 404 const BreakpointList &Target::GetBreakpointList(bool internal) const { 405 if (internal) 406 return m_internal_breakpoint_list; 407 else 408 return m_breakpoint_list; 409 } 410 411 BreakpointSP Target::GetBreakpointByID(break_id_t break_id) { 412 BreakpointSP bp_sp; 413 414 if (LLDB_BREAK_ID_IS_INTERNAL(break_id)) 415 bp_sp = m_internal_breakpoint_list.FindBreakpointByID(break_id); 416 else 417 bp_sp = m_breakpoint_list.FindBreakpointByID(break_id); 418 419 return bp_sp; 420 } 421 422 lldb::BreakpointSP 423 lldb_private::Target::CreateBreakpointAtUserEntry(Status &error) { 424 ModuleSP main_module_sp = GetExecutableModule(); 425 FileSpecList shared_lib_filter; 426 shared_lib_filter.Append(main_module_sp->GetFileSpec()); 427 llvm::SetVector<std::string, std::vector<std::string>, 428 std::unordered_set<std::string>> 429 entryPointNamesSet; 430 for (LanguageType lang_type : Language::GetSupportedLanguages()) { 431 Language *lang = Language::FindPlugin(lang_type); 432 if (!lang) { 433 error = Status::FromErrorString("Language not found\n"); 434 return lldb::BreakpointSP(); 435 } 436 std::string entryPointName = lang->GetUserEntryPointName().str(); 437 if (!entryPointName.empty()) 438 entryPointNamesSet.insert(entryPointName); 439 } 440 if (entryPointNamesSet.empty()) { 441 error = Status::FromErrorString("No entry point name found\n"); 442 return lldb::BreakpointSP(); 443 } 444 BreakpointSP bp_sp = CreateBreakpoint( 445 &shared_lib_filter, 446 /*containingSourceFiles=*/nullptr, entryPointNamesSet.takeVector(), 447 /*func_name_type_mask=*/eFunctionNameTypeFull, 448 /*language=*/eLanguageTypeUnknown, 449 /*offset=*/0, 450 /*skip_prologue=*/eLazyBoolNo, 451 /*internal=*/false, 452 /*hardware=*/false); 453 if (!bp_sp) { 454 error = Status::FromErrorString("Breakpoint creation failed.\n"); 455 return lldb::BreakpointSP(); 456 } 457 bp_sp->SetOneShot(true); 458 return bp_sp; 459 } 460 461 BreakpointSP Target::CreateSourceRegexBreakpoint( 462 const FileSpecList *containingModules, 463 const FileSpecList *source_file_spec_list, 464 const std::unordered_set<std::string> &function_names, 465 RegularExpression source_regex, bool internal, bool hardware, 466 LazyBool move_to_nearest_code) { 467 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList( 468 containingModules, source_file_spec_list)); 469 if (move_to_nearest_code == eLazyBoolCalculate) 470 move_to_nearest_code = GetMoveToNearestCode() ? eLazyBoolYes : eLazyBoolNo; 471 BreakpointResolverSP resolver_sp(new BreakpointResolverFileRegex( 472 nullptr, std::move(source_regex), function_names, 473 !static_cast<bool>(move_to_nearest_code))); 474 475 return CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true); 476 } 477 478 BreakpointSP Target::CreateBreakpoint(const FileSpecList *containingModules, 479 const FileSpec &file, uint32_t line_no, 480 uint32_t column, lldb::addr_t offset, 481 LazyBool check_inlines, 482 LazyBool skip_prologue, bool internal, 483 bool hardware, 484 LazyBool move_to_nearest_code) { 485 FileSpec remapped_file; 486 std::optional<llvm::StringRef> removed_prefix_opt = 487 GetSourcePathMap().ReverseRemapPath(file, remapped_file); 488 if (!removed_prefix_opt) 489 remapped_file = file; 490 491 if (check_inlines == eLazyBoolCalculate) { 492 const InlineStrategy inline_strategy = GetInlineStrategy(); 493 switch (inline_strategy) { 494 case eInlineBreakpointsNever: 495 check_inlines = eLazyBoolNo; 496 break; 497 498 case eInlineBreakpointsHeaders: 499 if (remapped_file.IsSourceImplementationFile()) 500 check_inlines = eLazyBoolNo; 501 else 502 check_inlines = eLazyBoolYes; 503 break; 504 505 case eInlineBreakpointsAlways: 506 check_inlines = eLazyBoolYes; 507 break; 508 } 509 } 510 SearchFilterSP filter_sp; 511 if (check_inlines == eLazyBoolNo) { 512 // Not checking for inlines, we are looking only for matching compile units 513 FileSpecList compile_unit_list; 514 compile_unit_list.Append(remapped_file); 515 filter_sp = GetSearchFilterForModuleAndCUList(containingModules, 516 &compile_unit_list); 517 } else { 518 filter_sp = GetSearchFilterForModuleList(containingModules); 519 } 520 if (skip_prologue == eLazyBoolCalculate) 521 skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo; 522 if (move_to_nearest_code == eLazyBoolCalculate) 523 move_to_nearest_code = GetMoveToNearestCode() ? eLazyBoolYes : eLazyBoolNo; 524 525 SourceLocationSpec location_spec(remapped_file, line_no, column, 526 check_inlines, 527 !static_cast<bool>(move_to_nearest_code)); 528 if (!location_spec) 529 return nullptr; 530 531 BreakpointResolverSP resolver_sp(new BreakpointResolverFileLine( 532 nullptr, offset, skip_prologue, location_spec, removed_prefix_opt)); 533 return CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true); 534 } 535 536 BreakpointSP Target::CreateBreakpoint(lldb::addr_t addr, bool internal, 537 bool hardware) { 538 Address so_addr; 539 540 // Check for any reason we want to move this breakpoint to other address. 541 addr = GetBreakableLoadAddress(addr); 542 543 // Attempt to resolve our load address if possible, though it is ok if it 544 // doesn't resolve to section/offset. 545 546 // Try and resolve as a load address if possible 547 GetSectionLoadList().ResolveLoadAddress(addr, so_addr); 548 if (!so_addr.IsValid()) { 549 // The address didn't resolve, so just set this as an absolute address 550 so_addr.SetOffset(addr); 551 } 552 BreakpointSP bp_sp(CreateBreakpoint(so_addr, internal, hardware)); 553 return bp_sp; 554 } 555 556 BreakpointSP Target::CreateBreakpoint(const Address &addr, bool internal, 557 bool hardware) { 558 SearchFilterSP filter_sp( 559 new SearchFilterForUnconstrainedSearches(shared_from_this())); 560 BreakpointResolverSP resolver_sp( 561 new BreakpointResolverAddress(nullptr, addr)); 562 return CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, false); 563 } 564 565 lldb::BreakpointSP 566 Target::CreateAddressInModuleBreakpoint(lldb::addr_t file_addr, bool internal, 567 const FileSpec &file_spec, 568 bool request_hardware) { 569 SearchFilterSP filter_sp( 570 new SearchFilterForUnconstrainedSearches(shared_from_this())); 571 BreakpointResolverSP resolver_sp(new BreakpointResolverAddress( 572 nullptr, file_addr, file_spec)); 573 return CreateBreakpoint(filter_sp, resolver_sp, internal, request_hardware, 574 false); 575 } 576 577 BreakpointSP Target::CreateBreakpoint( 578 const FileSpecList *containingModules, 579 const FileSpecList *containingSourceFiles, const char *func_name, 580 FunctionNameType func_name_type_mask, LanguageType language, 581 lldb::addr_t offset, LazyBool skip_prologue, bool internal, bool hardware) { 582 BreakpointSP bp_sp; 583 if (func_name) { 584 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList( 585 containingModules, containingSourceFiles)); 586 587 if (skip_prologue == eLazyBoolCalculate) 588 skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo; 589 if (language == lldb::eLanguageTypeUnknown) 590 language = GetLanguage().AsLanguageType(); 591 592 BreakpointResolverSP resolver_sp(new BreakpointResolverName( 593 nullptr, func_name, func_name_type_mask, language, Breakpoint::Exact, 594 offset, skip_prologue)); 595 bp_sp = CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true); 596 } 597 return bp_sp; 598 } 599 600 lldb::BreakpointSP 601 Target::CreateBreakpoint(const FileSpecList *containingModules, 602 const FileSpecList *containingSourceFiles, 603 const std::vector<std::string> &func_names, 604 FunctionNameType func_name_type_mask, 605 LanguageType language, lldb::addr_t offset, 606 LazyBool skip_prologue, bool internal, bool hardware) { 607 BreakpointSP bp_sp; 608 size_t num_names = func_names.size(); 609 if (num_names > 0) { 610 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList( 611 containingModules, containingSourceFiles)); 612 613 if (skip_prologue == eLazyBoolCalculate) 614 skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo; 615 if (language == lldb::eLanguageTypeUnknown) 616 language = GetLanguage().AsLanguageType(); 617 618 BreakpointResolverSP resolver_sp( 619 new BreakpointResolverName(nullptr, func_names, func_name_type_mask, 620 language, offset, skip_prologue)); 621 bp_sp = CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true); 622 } 623 return bp_sp; 624 } 625 626 BreakpointSP 627 Target::CreateBreakpoint(const FileSpecList *containingModules, 628 const FileSpecList *containingSourceFiles, 629 const char *func_names[], size_t num_names, 630 FunctionNameType func_name_type_mask, 631 LanguageType language, lldb::addr_t offset, 632 LazyBool skip_prologue, bool internal, bool hardware) { 633 BreakpointSP bp_sp; 634 if (num_names > 0) { 635 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList( 636 containingModules, containingSourceFiles)); 637 638 if (skip_prologue == eLazyBoolCalculate) { 639 if (offset == 0) 640 skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo; 641 else 642 skip_prologue = eLazyBoolNo; 643 } 644 if (language == lldb::eLanguageTypeUnknown) 645 language = GetLanguage().AsLanguageType(); 646 647 BreakpointResolverSP resolver_sp(new BreakpointResolverName( 648 nullptr, func_names, num_names, func_name_type_mask, language, offset, 649 skip_prologue)); 650 resolver_sp->SetOffset(offset); 651 bp_sp = CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true); 652 } 653 return bp_sp; 654 } 655 656 SearchFilterSP 657 Target::GetSearchFilterForModule(const FileSpec *containingModule) { 658 SearchFilterSP filter_sp; 659 if (containingModule != nullptr) { 660 // TODO: We should look into sharing module based search filters 661 // across many breakpoints like we do for the simple target based one 662 filter_sp = std::make_shared<SearchFilterByModule>(shared_from_this(), 663 *containingModule); 664 } else { 665 if (!m_search_filter_sp) 666 m_search_filter_sp = 667 std::make_shared<SearchFilterForUnconstrainedSearches>( 668 shared_from_this()); 669 filter_sp = m_search_filter_sp; 670 } 671 return filter_sp; 672 } 673 674 SearchFilterSP 675 Target::GetSearchFilterForModuleList(const FileSpecList *containingModules) { 676 SearchFilterSP filter_sp; 677 if (containingModules && containingModules->GetSize() != 0) { 678 // TODO: We should look into sharing module based search filters 679 // across many breakpoints like we do for the simple target based one 680 filter_sp = std::make_shared<SearchFilterByModuleList>(shared_from_this(), 681 *containingModules); 682 } else { 683 if (!m_search_filter_sp) 684 m_search_filter_sp = 685 std::make_shared<SearchFilterForUnconstrainedSearches>( 686 shared_from_this()); 687 filter_sp = m_search_filter_sp; 688 } 689 return filter_sp; 690 } 691 692 SearchFilterSP Target::GetSearchFilterForModuleAndCUList( 693 const FileSpecList *containingModules, 694 const FileSpecList *containingSourceFiles) { 695 if (containingSourceFiles == nullptr || containingSourceFiles->GetSize() == 0) 696 return GetSearchFilterForModuleList(containingModules); 697 698 SearchFilterSP filter_sp; 699 if (containingModules == nullptr) { 700 // We could make a special "CU List only SearchFilter". Better yet was if 701 // these could be composable, but that will take a little reworking. 702 703 filter_sp = std::make_shared<SearchFilterByModuleListAndCU>( 704 shared_from_this(), FileSpecList(), *containingSourceFiles); 705 } else { 706 filter_sp = std::make_shared<SearchFilterByModuleListAndCU>( 707 shared_from_this(), *containingModules, *containingSourceFiles); 708 } 709 return filter_sp; 710 } 711 712 BreakpointSP Target::CreateFuncRegexBreakpoint( 713 const FileSpecList *containingModules, 714 const FileSpecList *containingSourceFiles, RegularExpression func_regex, 715 lldb::LanguageType requested_language, LazyBool skip_prologue, 716 bool internal, bool hardware) { 717 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList( 718 containingModules, containingSourceFiles)); 719 bool skip = (skip_prologue == eLazyBoolCalculate) 720 ? GetSkipPrologue() 721 : static_cast<bool>(skip_prologue); 722 BreakpointResolverSP resolver_sp(new BreakpointResolverName( 723 nullptr, std::move(func_regex), requested_language, 0, skip)); 724 725 return CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true); 726 } 727 728 lldb::BreakpointSP 729 Target::CreateExceptionBreakpoint(enum lldb::LanguageType language, 730 bool catch_bp, bool throw_bp, bool internal, 731 Args *additional_args, Status *error) { 732 BreakpointSP exc_bkpt_sp = LanguageRuntime::CreateExceptionBreakpoint( 733 *this, language, catch_bp, throw_bp, internal); 734 if (exc_bkpt_sp && additional_args) { 735 BreakpointPreconditionSP precondition_sp = exc_bkpt_sp->GetPrecondition(); 736 if (precondition_sp && additional_args) { 737 if (error) 738 *error = precondition_sp->ConfigurePrecondition(*additional_args); 739 else 740 precondition_sp->ConfigurePrecondition(*additional_args); 741 } 742 } 743 return exc_bkpt_sp; 744 } 745 746 lldb::BreakpointSP Target::CreateScriptedBreakpoint( 747 const llvm::StringRef class_name, const FileSpecList *containingModules, 748 const FileSpecList *containingSourceFiles, bool internal, 749 bool request_hardware, StructuredData::ObjectSP extra_args_sp, 750 Status *creation_error) { 751 SearchFilterSP filter_sp; 752 753 lldb::SearchDepth depth = lldb::eSearchDepthTarget; 754 bool has_files = 755 containingSourceFiles && containingSourceFiles->GetSize() > 0; 756 bool has_modules = containingModules && containingModules->GetSize() > 0; 757 758 if (has_files && has_modules) { 759 filter_sp = GetSearchFilterForModuleAndCUList(containingModules, 760 containingSourceFiles); 761 } else if (has_files) { 762 filter_sp = 763 GetSearchFilterForModuleAndCUList(nullptr, containingSourceFiles); 764 } else if (has_modules) { 765 filter_sp = GetSearchFilterForModuleList(containingModules); 766 } else { 767 filter_sp = std::make_shared<SearchFilterForUnconstrainedSearches>( 768 shared_from_this()); 769 } 770 771 BreakpointResolverSP resolver_sp(new BreakpointResolverScripted( 772 nullptr, class_name, depth, StructuredDataImpl(extra_args_sp))); 773 return CreateBreakpoint(filter_sp, resolver_sp, internal, false, true); 774 } 775 776 BreakpointSP Target::CreateBreakpoint(SearchFilterSP &filter_sp, 777 BreakpointResolverSP &resolver_sp, 778 bool internal, bool request_hardware, 779 bool resolve_indirect_symbols) { 780 BreakpointSP bp_sp; 781 if (filter_sp && resolver_sp) { 782 const bool hardware = request_hardware || GetRequireHardwareBreakpoints(); 783 bp_sp.reset(new Breakpoint(*this, filter_sp, resolver_sp, hardware, 784 resolve_indirect_symbols)); 785 resolver_sp->SetBreakpoint(bp_sp); 786 AddBreakpoint(bp_sp, internal); 787 } 788 return bp_sp; 789 } 790 791 void Target::AddBreakpoint(lldb::BreakpointSP bp_sp, bool internal) { 792 if (!bp_sp) 793 return; 794 if (internal) 795 m_internal_breakpoint_list.Add(bp_sp, false); 796 else 797 m_breakpoint_list.Add(bp_sp, true); 798 799 Log *log = GetLog(LLDBLog::Breakpoints); 800 if (log) { 801 StreamString s; 802 bp_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose); 803 LLDB_LOGF(log, "Target::%s (internal = %s) => break_id = %s\n", 804 __FUNCTION__, bp_sp->IsInternal() ? "yes" : "no", s.GetData()); 805 } 806 807 bp_sp->ResolveBreakpoint(); 808 809 if (!internal) { 810 m_last_created_breakpoint = bp_sp; 811 } 812 } 813 814 void Target::AddNameToBreakpoint(BreakpointID &id, llvm::StringRef name, 815 Status &error) { 816 BreakpointSP bp_sp = 817 m_breakpoint_list.FindBreakpointByID(id.GetBreakpointID()); 818 if (!bp_sp) { 819 StreamString s; 820 id.GetDescription(&s, eDescriptionLevelBrief); 821 error = Status::FromErrorStringWithFormat("Could not find breakpoint %s", 822 s.GetData()); 823 return; 824 } 825 AddNameToBreakpoint(bp_sp, name, error); 826 } 827 828 void Target::AddNameToBreakpoint(BreakpointSP &bp_sp, llvm::StringRef name, 829 Status &error) { 830 if (!bp_sp) 831 return; 832 833 BreakpointName *bp_name = FindBreakpointName(ConstString(name), true, error); 834 if (!bp_name) 835 return; 836 837 bp_name->ConfigureBreakpoint(bp_sp); 838 bp_sp->AddName(name); 839 } 840 841 void Target::AddBreakpointName(std::unique_ptr<BreakpointName> bp_name) { 842 m_breakpoint_names.insert( 843 std::make_pair(bp_name->GetName(), std::move(bp_name))); 844 } 845 846 BreakpointName *Target::FindBreakpointName(ConstString name, bool can_create, 847 Status &error) { 848 BreakpointID::StringIsBreakpointName(name.GetStringRef(), error); 849 if (!error.Success()) 850 return nullptr; 851 852 BreakpointNameList::iterator iter = m_breakpoint_names.find(name); 853 if (iter != m_breakpoint_names.end()) { 854 return iter->second.get(); 855 } 856 857 if (!can_create) { 858 error = Status::FromErrorStringWithFormat( 859 "Breakpoint name \"%s\" doesn't exist and " 860 "can_create is false.", 861 name.AsCString()); 862 return nullptr; 863 } 864 865 return m_breakpoint_names 866 .insert(std::make_pair(name, std::make_unique<BreakpointName>(name))) 867 .first->second.get(); 868 } 869 870 void Target::DeleteBreakpointName(ConstString name) { 871 BreakpointNameList::iterator iter = m_breakpoint_names.find(name); 872 873 if (iter != m_breakpoint_names.end()) { 874 const char *name_cstr = name.AsCString(); 875 m_breakpoint_names.erase(iter); 876 for (auto bp_sp : m_breakpoint_list.Breakpoints()) 877 bp_sp->RemoveName(name_cstr); 878 } 879 } 880 881 void Target::RemoveNameFromBreakpoint(lldb::BreakpointSP &bp_sp, 882 ConstString name) { 883 bp_sp->RemoveName(name.AsCString()); 884 } 885 886 void Target::ConfigureBreakpointName( 887 BreakpointName &bp_name, const BreakpointOptions &new_options, 888 const BreakpointName::Permissions &new_permissions) { 889 bp_name.GetOptions().CopyOverSetOptions(new_options); 890 bp_name.GetPermissions().MergeInto(new_permissions); 891 ApplyNameToBreakpoints(bp_name); 892 } 893 894 void Target::ApplyNameToBreakpoints(BreakpointName &bp_name) { 895 llvm::Expected<std::vector<BreakpointSP>> expected_vector = 896 m_breakpoint_list.FindBreakpointsByName(bp_name.GetName().AsCString()); 897 898 if (!expected_vector) { 899 LLDB_LOG(GetLog(LLDBLog::Breakpoints), "invalid breakpoint name: {}", 900 llvm::toString(expected_vector.takeError())); 901 return; 902 } 903 904 for (auto bp_sp : *expected_vector) 905 bp_name.ConfigureBreakpoint(bp_sp); 906 } 907 908 void Target::GetBreakpointNames(std::vector<std::string> &names) { 909 names.clear(); 910 for (const auto& bp_name_entry : m_breakpoint_names) { 911 names.push_back(bp_name_entry.first.AsCString()); 912 } 913 llvm::sort(names); 914 } 915 916 bool Target::ProcessIsValid() { 917 return (m_process_sp && m_process_sp->IsAlive()); 918 } 919 920 static bool CheckIfWatchpointsSupported(Target *target, Status &error) { 921 std::optional<uint32_t> num_supported_hardware_watchpoints = 922 target->GetProcessSP()->GetWatchpointSlotCount(); 923 924 // If unable to determine the # of watchpoints available, 925 // assume they are supported. 926 if (!num_supported_hardware_watchpoints) 927 return true; 928 929 if (*num_supported_hardware_watchpoints == 0) { 930 error = Status::FromErrorStringWithFormat( 931 "Target supports (%u) hardware watchpoint slots.\n", 932 *num_supported_hardware_watchpoints); 933 return false; 934 } 935 return true; 936 } 937 938 // See also Watchpoint::SetWatchpointType(uint32_t type) and the 939 // OptionGroupWatchpoint::WatchType enum type. 940 WatchpointSP Target::CreateWatchpoint(lldb::addr_t addr, size_t size, 941 const CompilerType *type, uint32_t kind, 942 Status &error) { 943 Log *log = GetLog(LLDBLog::Watchpoints); 944 LLDB_LOGF(log, 945 "Target::%s (addr = 0x%8.8" PRIx64 " size = %" PRIu64 946 " type = %u)\n", 947 __FUNCTION__, addr, (uint64_t)size, kind); 948 949 WatchpointSP wp_sp; 950 if (!ProcessIsValid()) { 951 error = Status::FromErrorString("process is not alive"); 952 return wp_sp; 953 } 954 955 if (addr == LLDB_INVALID_ADDRESS || size == 0) { 956 if (size == 0) 957 error = Status::FromErrorString( 958 "cannot set a watchpoint with watch_size of 0"); 959 else 960 error = Status::FromErrorStringWithFormat( 961 "invalid watch address: %" PRIu64, addr); 962 return wp_sp; 963 } 964 965 if (!LLDB_WATCH_TYPE_IS_VALID(kind)) { 966 error = 967 Status::FromErrorStringWithFormat("invalid watchpoint type: %d", kind); 968 } 969 970 if (!CheckIfWatchpointsSupported(this, error)) 971 return wp_sp; 972 973 // Currently we only support one watchpoint per address, with total number of 974 // watchpoints limited by the hardware which the inferior is running on. 975 976 // Grab the list mutex while doing operations. 977 const bool notify = false; // Don't notify about all the state changes we do 978 // on creating the watchpoint. 979 980 // Mask off ignored bits from watchpoint address. 981 if (ABISP abi = m_process_sp->GetABI()) 982 addr = abi->FixDataAddress(addr); 983 984 // LWP_TODO this sequence is looking for an existing watchpoint 985 // at the exact same user-specified address, disables the new one 986 // if addr/size/type match. If type/size differ, disable old one. 987 // This isn't correct, we need both watchpoints to use a shared 988 // WatchpointResource in the target, and expand the WatchpointResource 989 // to handle the needs of both Watchpoints. 990 // Also, even if the addresses don't match, they may need to be 991 // supported by the same WatchpointResource, e.g. a watchpoint 992 // watching 1 byte at 0x102 and a watchpoint watching 1 byte at 0x103. 993 // They're in the same word and must be watched by a single hardware 994 // watchpoint register. 995 996 std::unique_lock<std::recursive_mutex> lock; 997 this->GetWatchpointList().GetListMutex(lock); 998 WatchpointSP matched_sp = m_watchpoint_list.FindByAddress(addr); 999 if (matched_sp) { 1000 size_t old_size = matched_sp->GetByteSize(); 1001 uint32_t old_type = 1002 (matched_sp->WatchpointRead() ? LLDB_WATCH_TYPE_READ : 0) | 1003 (matched_sp->WatchpointWrite() ? LLDB_WATCH_TYPE_WRITE : 0) | 1004 (matched_sp->WatchpointModify() ? LLDB_WATCH_TYPE_MODIFY : 0); 1005 // Return the existing watchpoint if both size and type match. 1006 if (size == old_size && kind == old_type) { 1007 wp_sp = matched_sp; 1008 wp_sp->SetEnabled(false, notify); 1009 } else { 1010 // Nil the matched watchpoint; we will be creating a new one. 1011 m_process_sp->DisableWatchpoint(matched_sp, notify); 1012 m_watchpoint_list.Remove(matched_sp->GetID(), true); 1013 } 1014 } 1015 1016 if (!wp_sp) { 1017 wp_sp = std::make_shared<Watchpoint>(*this, addr, size, type); 1018 wp_sp->SetWatchpointType(kind, notify); 1019 m_watchpoint_list.Add(wp_sp, true); 1020 } 1021 1022 error = m_process_sp->EnableWatchpoint(wp_sp, notify); 1023 LLDB_LOGF(log, "Target::%s (creation of watchpoint %s with id = %u)\n", 1024 __FUNCTION__, error.Success() ? "succeeded" : "failed", 1025 wp_sp->GetID()); 1026 1027 if (error.Fail()) { 1028 // Enabling the watchpoint on the device side failed. Remove the said 1029 // watchpoint from the list maintained by the target instance. 1030 m_watchpoint_list.Remove(wp_sp->GetID(), true); 1031 wp_sp.reset(); 1032 } else 1033 m_last_created_watchpoint = wp_sp; 1034 return wp_sp; 1035 } 1036 1037 void Target::RemoveAllowedBreakpoints() { 1038 Log *log = GetLog(LLDBLog::Breakpoints); 1039 LLDB_LOGF(log, "Target::%s \n", __FUNCTION__); 1040 1041 m_breakpoint_list.RemoveAllowed(true); 1042 1043 m_last_created_breakpoint.reset(); 1044 } 1045 1046 void Target::RemoveAllBreakpoints(bool internal_also) { 1047 Log *log = GetLog(LLDBLog::Breakpoints); 1048 LLDB_LOGF(log, "Target::%s (internal_also = %s)\n", __FUNCTION__, 1049 internal_also ? "yes" : "no"); 1050 1051 m_breakpoint_list.RemoveAll(true); 1052 if (internal_also) 1053 m_internal_breakpoint_list.RemoveAll(false); 1054 1055 m_last_created_breakpoint.reset(); 1056 } 1057 1058 void Target::DisableAllBreakpoints(bool internal_also) { 1059 Log *log = GetLog(LLDBLog::Breakpoints); 1060 LLDB_LOGF(log, "Target::%s (internal_also = %s)\n", __FUNCTION__, 1061 internal_also ? "yes" : "no"); 1062 1063 m_breakpoint_list.SetEnabledAll(false); 1064 if (internal_also) 1065 m_internal_breakpoint_list.SetEnabledAll(false); 1066 } 1067 1068 void Target::DisableAllowedBreakpoints() { 1069 Log *log = GetLog(LLDBLog::Breakpoints); 1070 LLDB_LOGF(log, "Target::%s", __FUNCTION__); 1071 1072 m_breakpoint_list.SetEnabledAllowed(false); 1073 } 1074 1075 void Target::EnableAllBreakpoints(bool internal_also) { 1076 Log *log = GetLog(LLDBLog::Breakpoints); 1077 LLDB_LOGF(log, "Target::%s (internal_also = %s)\n", __FUNCTION__, 1078 internal_also ? "yes" : "no"); 1079 1080 m_breakpoint_list.SetEnabledAll(true); 1081 if (internal_also) 1082 m_internal_breakpoint_list.SetEnabledAll(true); 1083 } 1084 1085 void Target::EnableAllowedBreakpoints() { 1086 Log *log = GetLog(LLDBLog::Breakpoints); 1087 LLDB_LOGF(log, "Target::%s", __FUNCTION__); 1088 1089 m_breakpoint_list.SetEnabledAllowed(true); 1090 } 1091 1092 bool Target::RemoveBreakpointByID(break_id_t break_id) { 1093 Log *log = GetLog(LLDBLog::Breakpoints); 1094 LLDB_LOGF(log, "Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__, 1095 break_id, LLDB_BREAK_ID_IS_INTERNAL(break_id) ? "yes" : "no"); 1096 1097 if (DisableBreakpointByID(break_id)) { 1098 if (LLDB_BREAK_ID_IS_INTERNAL(break_id)) 1099 m_internal_breakpoint_list.Remove(break_id, false); 1100 else { 1101 if (m_last_created_breakpoint) { 1102 if (m_last_created_breakpoint->GetID() == break_id) 1103 m_last_created_breakpoint.reset(); 1104 } 1105 m_breakpoint_list.Remove(break_id, true); 1106 } 1107 return true; 1108 } 1109 return false; 1110 } 1111 1112 bool Target::DisableBreakpointByID(break_id_t break_id) { 1113 Log *log = GetLog(LLDBLog::Breakpoints); 1114 LLDB_LOGF(log, "Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__, 1115 break_id, LLDB_BREAK_ID_IS_INTERNAL(break_id) ? "yes" : "no"); 1116 1117 BreakpointSP bp_sp; 1118 1119 if (LLDB_BREAK_ID_IS_INTERNAL(break_id)) 1120 bp_sp = m_internal_breakpoint_list.FindBreakpointByID(break_id); 1121 else 1122 bp_sp = m_breakpoint_list.FindBreakpointByID(break_id); 1123 if (bp_sp) { 1124 bp_sp->SetEnabled(false); 1125 return true; 1126 } 1127 return false; 1128 } 1129 1130 bool Target::EnableBreakpointByID(break_id_t break_id) { 1131 Log *log = GetLog(LLDBLog::Breakpoints); 1132 LLDB_LOGF(log, "Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__, 1133 break_id, LLDB_BREAK_ID_IS_INTERNAL(break_id) ? "yes" : "no"); 1134 1135 BreakpointSP bp_sp; 1136 1137 if (LLDB_BREAK_ID_IS_INTERNAL(break_id)) 1138 bp_sp = m_internal_breakpoint_list.FindBreakpointByID(break_id); 1139 else 1140 bp_sp = m_breakpoint_list.FindBreakpointByID(break_id); 1141 1142 if (bp_sp) { 1143 bp_sp->SetEnabled(true); 1144 return true; 1145 } 1146 return false; 1147 } 1148 1149 void Target::ResetBreakpointHitCounts() { 1150 GetBreakpointList().ResetHitCounts(); 1151 } 1152 1153 Status Target::SerializeBreakpointsToFile(const FileSpec &file, 1154 const BreakpointIDList &bp_ids, 1155 bool append) { 1156 Status error; 1157 1158 if (!file) { 1159 error = Status::FromErrorString("Invalid FileSpec."); 1160 return error; 1161 } 1162 1163 std::string path(file.GetPath()); 1164 StructuredData::ObjectSP input_data_sp; 1165 1166 StructuredData::ArraySP break_store_sp; 1167 StructuredData::Array *break_store_ptr = nullptr; 1168 1169 if (append) { 1170 input_data_sp = StructuredData::ParseJSONFromFile(file, error); 1171 if (error.Success()) { 1172 break_store_ptr = input_data_sp->GetAsArray(); 1173 if (!break_store_ptr) { 1174 error = Status::FromErrorStringWithFormat( 1175 "Tried to append to invalid input file %s", path.c_str()); 1176 return error; 1177 } 1178 } 1179 } 1180 1181 if (!break_store_ptr) { 1182 break_store_sp = std::make_shared<StructuredData::Array>(); 1183 break_store_ptr = break_store_sp.get(); 1184 } 1185 1186 StreamFile out_file(path.c_str(), 1187 File::eOpenOptionTruncate | File::eOpenOptionWriteOnly | 1188 File::eOpenOptionCanCreate | 1189 File::eOpenOptionCloseOnExec, 1190 lldb::eFilePermissionsFileDefault); 1191 if (!out_file.GetFile().IsValid()) { 1192 error = Status::FromErrorStringWithFormat("Unable to open output file: %s.", 1193 path.c_str()); 1194 return error; 1195 } 1196 1197 std::unique_lock<std::recursive_mutex> lock; 1198 GetBreakpointList().GetListMutex(lock); 1199 1200 if (bp_ids.GetSize() == 0) { 1201 const BreakpointList &breakpoints = GetBreakpointList(); 1202 1203 size_t num_breakpoints = breakpoints.GetSize(); 1204 for (size_t i = 0; i < num_breakpoints; i++) { 1205 Breakpoint *bp = breakpoints.GetBreakpointAtIndex(i).get(); 1206 StructuredData::ObjectSP bkpt_save_sp = bp->SerializeToStructuredData(); 1207 // If a breakpoint can't serialize it, just ignore it for now: 1208 if (bkpt_save_sp) 1209 break_store_ptr->AddItem(bkpt_save_sp); 1210 } 1211 } else { 1212 1213 std::unordered_set<lldb::break_id_t> processed_bkpts; 1214 const size_t count = bp_ids.GetSize(); 1215 for (size_t i = 0; i < count; ++i) { 1216 BreakpointID cur_bp_id = bp_ids.GetBreakpointIDAtIndex(i); 1217 lldb::break_id_t bp_id = cur_bp_id.GetBreakpointID(); 1218 1219 if (bp_id != LLDB_INVALID_BREAK_ID) { 1220 // Only do each breakpoint once: 1221 std::pair<std::unordered_set<lldb::break_id_t>::iterator, bool> 1222 insert_result = processed_bkpts.insert(bp_id); 1223 if (!insert_result.second) 1224 continue; 1225 1226 Breakpoint *bp = GetBreakpointByID(bp_id).get(); 1227 StructuredData::ObjectSP bkpt_save_sp = bp->SerializeToStructuredData(); 1228 // If the user explicitly asked to serialize a breakpoint, and we 1229 // can't, then raise an error: 1230 if (!bkpt_save_sp) { 1231 error = Status::FromErrorStringWithFormat( 1232 "Unable to serialize breakpoint %d", bp_id); 1233 return error; 1234 } 1235 break_store_ptr->AddItem(bkpt_save_sp); 1236 } 1237 } 1238 } 1239 1240 break_store_ptr->Dump(out_file, false); 1241 out_file.PutChar('\n'); 1242 return error; 1243 } 1244 1245 Status Target::CreateBreakpointsFromFile(const FileSpec &file, 1246 BreakpointIDList &new_bps) { 1247 std::vector<std::string> no_names; 1248 return CreateBreakpointsFromFile(file, no_names, new_bps); 1249 } 1250 1251 Status Target::CreateBreakpointsFromFile(const FileSpec &file, 1252 std::vector<std::string> &names, 1253 BreakpointIDList &new_bps) { 1254 std::unique_lock<std::recursive_mutex> lock; 1255 GetBreakpointList().GetListMutex(lock); 1256 1257 Status error; 1258 StructuredData::ObjectSP input_data_sp = 1259 StructuredData::ParseJSONFromFile(file, error); 1260 if (!error.Success()) { 1261 return error; 1262 } else if (!input_data_sp || !input_data_sp->IsValid()) { 1263 error = Status::FromErrorStringWithFormat( 1264 "Invalid JSON from input file: %s.", file.GetPath().c_str()); 1265 return error; 1266 } 1267 1268 StructuredData::Array *bkpt_array = input_data_sp->GetAsArray(); 1269 if (!bkpt_array) { 1270 error = Status::FromErrorStringWithFormat( 1271 "Invalid breakpoint data from input file: %s.", file.GetPath().c_str()); 1272 return error; 1273 } 1274 1275 size_t num_bkpts = bkpt_array->GetSize(); 1276 size_t num_names = names.size(); 1277 1278 for (size_t i = 0; i < num_bkpts; i++) { 1279 StructuredData::ObjectSP bkpt_object_sp = bkpt_array->GetItemAtIndex(i); 1280 // Peel off the breakpoint key, and feed the rest to the Breakpoint: 1281 StructuredData::Dictionary *bkpt_dict = bkpt_object_sp->GetAsDictionary(); 1282 if (!bkpt_dict) { 1283 error = Status::FromErrorStringWithFormat( 1284 "Invalid breakpoint data for element %zu from input file: %s.", i, 1285 file.GetPath().c_str()); 1286 return error; 1287 } 1288 StructuredData::ObjectSP bkpt_data_sp = 1289 bkpt_dict->GetValueForKey(Breakpoint::GetSerializationKey()); 1290 if (num_names && 1291 !Breakpoint::SerializedBreakpointMatchesNames(bkpt_data_sp, names)) 1292 continue; 1293 1294 BreakpointSP bkpt_sp = Breakpoint::CreateFromStructuredData( 1295 shared_from_this(), bkpt_data_sp, error); 1296 if (!error.Success()) { 1297 error = Status::FromErrorStringWithFormat( 1298 "Error restoring breakpoint %zu from %s: %s.", i, 1299 file.GetPath().c_str(), error.AsCString()); 1300 return error; 1301 } 1302 new_bps.AddBreakpointID(BreakpointID(bkpt_sp->GetID())); 1303 } 1304 return error; 1305 } 1306 1307 // The flag 'end_to_end', default to true, signifies that the operation is 1308 // performed end to end, for both the debugger and the debuggee. 1309 1310 // Assumption: Caller holds the list mutex lock for m_watchpoint_list for end 1311 // to end operations. 1312 bool Target::RemoveAllWatchpoints(bool end_to_end) { 1313 Log *log = GetLog(LLDBLog::Watchpoints); 1314 LLDB_LOGF(log, "Target::%s\n", __FUNCTION__); 1315 1316 if (!end_to_end) { 1317 m_watchpoint_list.RemoveAll(true); 1318 return true; 1319 } 1320 1321 // Otherwise, it's an end to end operation. 1322 1323 if (!ProcessIsValid()) 1324 return false; 1325 1326 for (WatchpointSP wp_sp : m_watchpoint_list.Watchpoints()) { 1327 if (!wp_sp) 1328 return false; 1329 1330 Status rc = m_process_sp->DisableWatchpoint(wp_sp); 1331 if (rc.Fail()) 1332 return false; 1333 } 1334 m_watchpoint_list.RemoveAll(true); 1335 m_last_created_watchpoint.reset(); 1336 return true; // Success! 1337 } 1338 1339 // Assumption: Caller holds the list mutex lock for m_watchpoint_list for end 1340 // to end operations. 1341 bool Target::DisableAllWatchpoints(bool end_to_end) { 1342 Log *log = GetLog(LLDBLog::Watchpoints); 1343 LLDB_LOGF(log, "Target::%s\n", __FUNCTION__); 1344 1345 if (!end_to_end) { 1346 m_watchpoint_list.SetEnabledAll(false); 1347 return true; 1348 } 1349 1350 // Otherwise, it's an end to end operation. 1351 1352 if (!ProcessIsValid()) 1353 return false; 1354 1355 for (WatchpointSP wp_sp : m_watchpoint_list.Watchpoints()) { 1356 if (!wp_sp) 1357 return false; 1358 1359 Status rc = m_process_sp->DisableWatchpoint(wp_sp); 1360 if (rc.Fail()) 1361 return false; 1362 } 1363 return true; // Success! 1364 } 1365 1366 // Assumption: Caller holds the list mutex lock for m_watchpoint_list for end 1367 // to end operations. 1368 bool Target::EnableAllWatchpoints(bool end_to_end) { 1369 Log *log = GetLog(LLDBLog::Watchpoints); 1370 LLDB_LOGF(log, "Target::%s\n", __FUNCTION__); 1371 1372 if (!end_to_end) { 1373 m_watchpoint_list.SetEnabledAll(true); 1374 return true; 1375 } 1376 1377 // Otherwise, it's an end to end operation. 1378 1379 if (!ProcessIsValid()) 1380 return false; 1381 1382 for (WatchpointSP wp_sp : m_watchpoint_list.Watchpoints()) { 1383 if (!wp_sp) 1384 return false; 1385 1386 Status rc = m_process_sp->EnableWatchpoint(wp_sp); 1387 if (rc.Fail()) 1388 return false; 1389 } 1390 return true; // Success! 1391 } 1392 1393 // Assumption: Caller holds the list mutex lock for m_watchpoint_list. 1394 bool Target::ClearAllWatchpointHitCounts() { 1395 Log *log = GetLog(LLDBLog::Watchpoints); 1396 LLDB_LOGF(log, "Target::%s\n", __FUNCTION__); 1397 1398 for (WatchpointSP wp_sp : m_watchpoint_list.Watchpoints()) { 1399 if (!wp_sp) 1400 return false; 1401 1402 wp_sp->ResetHitCount(); 1403 } 1404 return true; // Success! 1405 } 1406 1407 // Assumption: Caller holds the list mutex lock for m_watchpoint_list. 1408 bool Target::ClearAllWatchpointHistoricValues() { 1409 Log *log = GetLog(LLDBLog::Watchpoints); 1410 LLDB_LOGF(log, "Target::%s\n", __FUNCTION__); 1411 1412 for (WatchpointSP wp_sp : m_watchpoint_list.Watchpoints()) { 1413 if (!wp_sp) 1414 return false; 1415 1416 wp_sp->ResetHistoricValues(); 1417 } 1418 return true; // Success! 1419 } 1420 1421 // Assumption: Caller holds the list mutex lock for m_watchpoint_list during 1422 // these operations. 1423 bool Target::IgnoreAllWatchpoints(uint32_t ignore_count) { 1424 Log *log = GetLog(LLDBLog::Watchpoints); 1425 LLDB_LOGF(log, "Target::%s\n", __FUNCTION__); 1426 1427 if (!ProcessIsValid()) 1428 return false; 1429 1430 for (WatchpointSP wp_sp : m_watchpoint_list.Watchpoints()) { 1431 if (!wp_sp) 1432 return false; 1433 1434 wp_sp->SetIgnoreCount(ignore_count); 1435 } 1436 return true; // Success! 1437 } 1438 1439 // Assumption: Caller holds the list mutex lock for m_watchpoint_list. 1440 bool Target::DisableWatchpointByID(lldb::watch_id_t watch_id) { 1441 Log *log = GetLog(LLDBLog::Watchpoints); 1442 LLDB_LOGF(log, "Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id); 1443 1444 if (!ProcessIsValid()) 1445 return false; 1446 1447 WatchpointSP wp_sp = m_watchpoint_list.FindByID(watch_id); 1448 if (wp_sp) { 1449 Status rc = m_process_sp->DisableWatchpoint(wp_sp); 1450 if (rc.Success()) 1451 return true; 1452 1453 // Else, fallthrough. 1454 } 1455 return false; 1456 } 1457 1458 // Assumption: Caller holds the list mutex lock for m_watchpoint_list. 1459 bool Target::EnableWatchpointByID(lldb::watch_id_t watch_id) { 1460 Log *log = GetLog(LLDBLog::Watchpoints); 1461 LLDB_LOGF(log, "Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id); 1462 1463 if (!ProcessIsValid()) 1464 return false; 1465 1466 WatchpointSP wp_sp = m_watchpoint_list.FindByID(watch_id); 1467 if (wp_sp) { 1468 Status rc = m_process_sp->EnableWatchpoint(wp_sp); 1469 if (rc.Success()) 1470 return true; 1471 1472 // Else, fallthrough. 1473 } 1474 return false; 1475 } 1476 1477 // Assumption: Caller holds the list mutex lock for m_watchpoint_list. 1478 bool Target::RemoveWatchpointByID(lldb::watch_id_t watch_id) { 1479 Log *log = GetLog(LLDBLog::Watchpoints); 1480 LLDB_LOGF(log, "Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id); 1481 1482 WatchpointSP watch_to_remove_sp = m_watchpoint_list.FindByID(watch_id); 1483 if (watch_to_remove_sp == m_last_created_watchpoint) 1484 m_last_created_watchpoint.reset(); 1485 1486 if (DisableWatchpointByID(watch_id)) { 1487 m_watchpoint_list.Remove(watch_id, true); 1488 return true; 1489 } 1490 return false; 1491 } 1492 1493 // Assumption: Caller holds the list mutex lock for m_watchpoint_list. 1494 bool Target::IgnoreWatchpointByID(lldb::watch_id_t watch_id, 1495 uint32_t ignore_count) { 1496 Log *log = GetLog(LLDBLog::Watchpoints); 1497 LLDB_LOGF(log, "Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id); 1498 1499 if (!ProcessIsValid()) 1500 return false; 1501 1502 WatchpointSP wp_sp = m_watchpoint_list.FindByID(watch_id); 1503 if (wp_sp) { 1504 wp_sp->SetIgnoreCount(ignore_count); 1505 return true; 1506 } 1507 return false; 1508 } 1509 1510 ModuleSP Target::GetExecutableModule() { 1511 // search for the first executable in the module list 1512 for (size_t i = 0; i < m_images.GetSize(); ++i) { 1513 ModuleSP module_sp = m_images.GetModuleAtIndex(i); 1514 lldb_private::ObjectFile *obj = module_sp->GetObjectFile(); 1515 if (obj == nullptr) 1516 continue; 1517 if (obj->GetType() == ObjectFile::Type::eTypeExecutable) 1518 return module_sp; 1519 } 1520 // as fall back return the first module loaded 1521 return m_images.GetModuleAtIndex(0); 1522 } 1523 1524 Module *Target::GetExecutableModulePointer() { 1525 return GetExecutableModule().get(); 1526 } 1527 1528 static void LoadScriptingResourceForModule(const ModuleSP &module_sp, 1529 Target *target) { 1530 Status error; 1531 StreamString feedback_stream; 1532 if (module_sp && !module_sp->LoadScriptingResourceInTarget(target, error, 1533 feedback_stream)) { 1534 if (error.AsCString()) 1535 target->GetDebugger().GetErrorStream().Printf( 1536 "unable to load scripting data for module %s - error reported was " 1537 "%s\n", 1538 module_sp->GetFileSpec().GetFileNameStrippingExtension().GetCString(), 1539 error.AsCString()); 1540 } 1541 if (feedback_stream.GetSize()) 1542 target->GetDebugger().GetErrorStream().Printf("%s\n", 1543 feedback_stream.GetData()); 1544 } 1545 1546 void Target::ClearModules(bool delete_locations) { 1547 ModulesDidUnload(m_images, delete_locations); 1548 m_section_load_history.Clear(); 1549 m_images.Clear(); 1550 m_scratch_type_system_map.Clear(); 1551 } 1552 1553 void Target::DidExec() { 1554 // When a process exec's we need to know about it so we can do some cleanup. 1555 m_breakpoint_list.RemoveInvalidLocations(m_arch.GetSpec()); 1556 m_internal_breakpoint_list.RemoveInvalidLocations(m_arch.GetSpec()); 1557 } 1558 1559 void Target::SetExecutableModule(ModuleSP &executable_sp, 1560 LoadDependentFiles load_dependent_files) { 1561 Log *log = GetLog(LLDBLog::Target); 1562 ClearModules(false); 1563 1564 if (executable_sp) { 1565 ElapsedTime elapsed(m_stats.GetCreateTime()); 1566 LLDB_SCOPED_TIMERF("Target::SetExecutableModule (executable = '%s')", 1567 executable_sp->GetFileSpec().GetPath().c_str()); 1568 1569 const bool notify = true; 1570 m_images.Append(executable_sp, 1571 notify); // The first image is our executable file 1572 1573 // If we haven't set an architecture yet, reset our architecture based on 1574 // what we found in the executable module. 1575 if (!m_arch.GetSpec().IsValid()) { 1576 m_arch = executable_sp->GetArchitecture(); 1577 LLDB_LOG(log, 1578 "Target::SetExecutableModule setting architecture to {0} ({1}) " 1579 "based on executable file", 1580 m_arch.GetSpec().GetArchitectureName(), 1581 m_arch.GetSpec().GetTriple().getTriple()); 1582 } 1583 1584 ObjectFile *executable_objfile = executable_sp->GetObjectFile(); 1585 bool load_dependents = true; 1586 switch (load_dependent_files) { 1587 case eLoadDependentsDefault: 1588 load_dependents = executable_sp->IsExecutable(); 1589 break; 1590 case eLoadDependentsYes: 1591 load_dependents = true; 1592 break; 1593 case eLoadDependentsNo: 1594 load_dependents = false; 1595 break; 1596 } 1597 1598 if (executable_objfile && load_dependents) { 1599 // FileSpecList is not thread safe and needs to be synchronized. 1600 FileSpecList dependent_files; 1601 std::mutex dependent_files_mutex; 1602 1603 // ModuleList is thread safe. 1604 ModuleList added_modules; 1605 1606 auto GetDependentModules = [&](FileSpec dependent_file_spec) { 1607 FileSpec platform_dependent_file_spec; 1608 if (m_platform_sp) 1609 m_platform_sp->GetFileWithUUID(dependent_file_spec, nullptr, 1610 platform_dependent_file_spec); 1611 else 1612 platform_dependent_file_spec = dependent_file_spec; 1613 1614 ModuleSpec module_spec(platform_dependent_file_spec, m_arch.GetSpec()); 1615 ModuleSP image_module_sp( 1616 GetOrCreateModule(module_spec, false /* notify */)); 1617 if (image_module_sp) { 1618 added_modules.AppendIfNeeded(image_module_sp, false); 1619 ObjectFile *objfile = image_module_sp->GetObjectFile(); 1620 if (objfile) { 1621 // Create a local copy of the dependent file list so we don't have 1622 // to lock for the whole duration of GetDependentModules. 1623 FileSpecList dependent_files_copy; 1624 { 1625 std::lock_guard<std::mutex> guard(dependent_files_mutex); 1626 dependent_files_copy = dependent_files; 1627 } 1628 1629 // Remember the size of the local copy so we can append only the 1630 // modules that have been added by GetDependentModules. 1631 const size_t previous_dependent_files = 1632 dependent_files_copy.GetSize(); 1633 1634 objfile->GetDependentModules(dependent_files_copy); 1635 1636 { 1637 std::lock_guard<std::mutex> guard(dependent_files_mutex); 1638 for (size_t i = previous_dependent_files; 1639 i < dependent_files_copy.GetSize(); ++i) 1640 dependent_files.AppendIfUnique( 1641 dependent_files_copy.GetFileSpecAtIndex(i)); 1642 } 1643 } 1644 } 1645 }; 1646 1647 executable_objfile->GetDependentModules(dependent_files); 1648 1649 llvm::ThreadPoolTaskGroup task_group(Debugger::GetThreadPool()); 1650 for (uint32_t i = 0; i < dependent_files.GetSize(); i++) { 1651 // Process all currently known dependencies in parallel in the innermost 1652 // loop. This may create newly discovered dependencies to be appended to 1653 // dependent_files. We'll deal with these files during the next 1654 // iteration of the outermost loop. 1655 { 1656 std::lock_guard<std::mutex> guard(dependent_files_mutex); 1657 for (; i < dependent_files.GetSize(); i++) 1658 task_group.async(GetDependentModules, 1659 dependent_files.GetFileSpecAtIndex(i)); 1660 } 1661 task_group.wait(); 1662 } 1663 ModulesDidLoad(added_modules); 1664 } 1665 } 1666 } 1667 1668 bool Target::SetArchitecture(const ArchSpec &arch_spec, bool set_platform, 1669 bool merge) { 1670 Log *log = GetLog(LLDBLog::Target); 1671 bool missing_local_arch = !m_arch.GetSpec().IsValid(); 1672 bool replace_local_arch = true; 1673 bool compatible_local_arch = false; 1674 ArchSpec other(arch_spec); 1675 1676 // Changing the architecture might mean that the currently selected platform 1677 // isn't compatible. Set the platform correctly if we are asked to do so, 1678 // otherwise assume the user will set the platform manually. 1679 if (set_platform) { 1680 if (other.IsValid()) { 1681 auto platform_sp = GetPlatform(); 1682 if (!platform_sp || !platform_sp->IsCompatibleArchitecture( 1683 other, {}, ArchSpec::CompatibleMatch, nullptr)) { 1684 ArchSpec platform_arch; 1685 if (PlatformSP arch_platform_sp = 1686 GetDebugger().GetPlatformList().GetOrCreate(other, {}, 1687 &platform_arch)) { 1688 SetPlatform(arch_platform_sp); 1689 if (platform_arch.IsValid()) 1690 other = platform_arch; 1691 } 1692 } 1693 } 1694 } 1695 1696 if (!missing_local_arch) { 1697 if (merge && m_arch.GetSpec().IsCompatibleMatch(arch_spec)) { 1698 other.MergeFrom(m_arch.GetSpec()); 1699 1700 if (m_arch.GetSpec().IsCompatibleMatch(other)) { 1701 compatible_local_arch = true; 1702 1703 if (m_arch.GetSpec().GetTriple() == other.GetTriple()) 1704 replace_local_arch = false; 1705 } 1706 } 1707 } 1708 1709 if (compatible_local_arch || missing_local_arch) { 1710 // If we haven't got a valid arch spec, or the architectures are compatible 1711 // update the architecture, unless the one we already have is more 1712 // specified 1713 if (replace_local_arch) 1714 m_arch = other; 1715 LLDB_LOG(log, 1716 "Target::SetArchitecture merging compatible arch; arch " 1717 "is now {0} ({1})", 1718 m_arch.GetSpec().GetArchitectureName(), 1719 m_arch.GetSpec().GetTriple().getTriple()); 1720 return true; 1721 } 1722 1723 // If we have an executable file, try to reset the executable to the desired 1724 // architecture 1725 LLDB_LOGF( 1726 log, 1727 "Target::SetArchitecture changing architecture to %s (%s) from %s (%s)", 1728 arch_spec.GetArchitectureName(), 1729 arch_spec.GetTriple().getTriple().c_str(), 1730 m_arch.GetSpec().GetArchitectureName(), 1731 m_arch.GetSpec().GetTriple().getTriple().c_str()); 1732 m_arch = other; 1733 ModuleSP executable_sp = GetExecutableModule(); 1734 1735 ClearModules(true); 1736 // Need to do something about unsetting breakpoints. 1737 1738 if (executable_sp) { 1739 LLDB_LOGF(log, 1740 "Target::SetArchitecture Trying to select executable file " 1741 "architecture %s (%s)", 1742 arch_spec.GetArchitectureName(), 1743 arch_spec.GetTriple().getTriple().c_str()); 1744 ModuleSpec module_spec(executable_sp->GetFileSpec(), other); 1745 FileSpecList search_paths = GetExecutableSearchPaths(); 1746 Status error = ModuleList::GetSharedModule(module_spec, executable_sp, 1747 &search_paths, nullptr, nullptr); 1748 1749 if (!error.Fail() && executable_sp) { 1750 SetExecutableModule(executable_sp, eLoadDependentsYes); 1751 return true; 1752 } 1753 } 1754 return false; 1755 } 1756 1757 bool Target::MergeArchitecture(const ArchSpec &arch_spec) { 1758 Log *log = GetLog(LLDBLog::Target); 1759 if (arch_spec.IsValid()) { 1760 if (m_arch.GetSpec().IsCompatibleMatch(arch_spec)) { 1761 // The current target arch is compatible with "arch_spec", see if we can 1762 // improve our current architecture using bits from "arch_spec" 1763 1764 LLDB_LOGF(log, 1765 "Target::MergeArchitecture target has arch %s, merging with " 1766 "arch %s", 1767 m_arch.GetSpec().GetTriple().getTriple().c_str(), 1768 arch_spec.GetTriple().getTriple().c_str()); 1769 1770 // Merge bits from arch_spec into "merged_arch" and set our architecture 1771 ArchSpec merged_arch(m_arch.GetSpec()); 1772 merged_arch.MergeFrom(arch_spec); 1773 return SetArchitecture(merged_arch); 1774 } else { 1775 // The new architecture is different, we just need to replace it 1776 return SetArchitecture(arch_spec); 1777 } 1778 } 1779 return false; 1780 } 1781 1782 void Target::NotifyWillClearList(const ModuleList &module_list) {} 1783 1784 void Target::NotifyModuleAdded(const ModuleList &module_list, 1785 const ModuleSP &module_sp) { 1786 // A module is being added to this target for the first time 1787 if (m_valid) { 1788 ModuleList my_module_list; 1789 my_module_list.Append(module_sp); 1790 ModulesDidLoad(my_module_list); 1791 } 1792 } 1793 1794 void Target::NotifyModuleRemoved(const ModuleList &module_list, 1795 const ModuleSP &module_sp) { 1796 // A module is being removed from this target. 1797 if (m_valid) { 1798 ModuleList my_module_list; 1799 my_module_list.Append(module_sp); 1800 ModulesDidUnload(my_module_list, false); 1801 } 1802 } 1803 1804 void Target::NotifyModuleUpdated(const ModuleList &module_list, 1805 const ModuleSP &old_module_sp, 1806 const ModuleSP &new_module_sp) { 1807 // A module is replacing an already added module 1808 if (m_valid) { 1809 m_breakpoint_list.UpdateBreakpointsWhenModuleIsReplaced(old_module_sp, 1810 new_module_sp); 1811 m_internal_breakpoint_list.UpdateBreakpointsWhenModuleIsReplaced( 1812 old_module_sp, new_module_sp); 1813 } 1814 } 1815 1816 void Target::NotifyModulesRemoved(lldb_private::ModuleList &module_list) { 1817 ModulesDidUnload(module_list, false); 1818 } 1819 1820 void Target::ModulesDidLoad(ModuleList &module_list) { 1821 const size_t num_images = module_list.GetSize(); 1822 if (m_valid && num_images) { 1823 for (size_t idx = 0; idx < num_images; ++idx) { 1824 ModuleSP module_sp(module_list.GetModuleAtIndex(idx)); 1825 LoadScriptingResourceForModule(module_sp, this); 1826 LoadTypeSummariesForModule(module_sp); 1827 LoadFormattersForModule(module_sp); 1828 } 1829 m_breakpoint_list.UpdateBreakpoints(module_list, true, false); 1830 m_internal_breakpoint_list.UpdateBreakpoints(module_list, true, false); 1831 if (m_process_sp) { 1832 m_process_sp->ModulesDidLoad(module_list); 1833 } 1834 auto data_sp = 1835 std::make_shared<TargetEventData>(shared_from_this(), module_list); 1836 BroadcastEvent(eBroadcastBitModulesLoaded, data_sp); 1837 } 1838 } 1839 1840 void Target::SymbolsDidLoad(ModuleList &module_list) { 1841 if (m_valid && module_list.GetSize()) { 1842 if (m_process_sp) { 1843 for (LanguageRuntime *runtime : m_process_sp->GetLanguageRuntimes()) { 1844 runtime->SymbolsDidLoad(module_list); 1845 } 1846 } 1847 1848 m_breakpoint_list.UpdateBreakpoints(module_list, true, false); 1849 m_internal_breakpoint_list.UpdateBreakpoints(module_list, true, false); 1850 auto data_sp = 1851 std::make_shared<TargetEventData>(shared_from_this(), module_list); 1852 BroadcastEvent(eBroadcastBitSymbolsLoaded, data_sp); 1853 } 1854 } 1855 1856 void Target::ModulesDidUnload(ModuleList &module_list, bool delete_locations) { 1857 if (m_valid && module_list.GetSize()) { 1858 UnloadModuleSections(module_list); 1859 auto data_sp = 1860 std::make_shared<TargetEventData>(shared_from_this(), module_list); 1861 BroadcastEvent(eBroadcastBitModulesUnloaded, data_sp); 1862 m_breakpoint_list.UpdateBreakpoints(module_list, false, delete_locations); 1863 m_internal_breakpoint_list.UpdateBreakpoints(module_list, false, 1864 delete_locations); 1865 1866 // If a module was torn down it will have torn down the 'TypeSystemClang's 1867 // that we used as source 'ASTContext's for the persistent variables in 1868 // the current target. Those would now be unsafe to access because the 1869 // 'DeclOrigin' are now possibly stale. Thus clear all persistent 1870 // variables. We only want to flush 'TypeSystem's if the module being 1871 // unloaded was capable of describing a source type. JITted module unloads 1872 // happen frequently for Objective-C utility functions or the REPL and rely 1873 // on the persistent variables to stick around. 1874 const bool should_flush_type_systems = 1875 module_list.AnyOf([](lldb_private::Module &module) { 1876 auto *object_file = module.GetObjectFile(); 1877 1878 if (!object_file) 1879 return false; 1880 1881 auto type = object_file->GetType(); 1882 1883 // eTypeExecutable: when debugged binary was rebuilt 1884 // eTypeSharedLibrary: if dylib was re-loaded 1885 return module.FileHasChanged() && 1886 (type == ObjectFile::eTypeObjectFile || 1887 type == ObjectFile::eTypeExecutable || 1888 type == ObjectFile::eTypeSharedLibrary); 1889 }); 1890 1891 if (should_flush_type_systems) 1892 m_scratch_type_system_map.Clear(); 1893 } 1894 } 1895 1896 bool Target::ModuleIsExcludedForUnconstrainedSearches( 1897 const FileSpec &module_file_spec) { 1898 if (GetBreakpointsConsultPlatformAvoidList()) { 1899 ModuleList matchingModules; 1900 ModuleSpec module_spec(module_file_spec); 1901 GetImages().FindModules(module_spec, matchingModules); 1902 size_t num_modules = matchingModules.GetSize(); 1903 1904 // If there is more than one module for this file spec, only 1905 // return true if ALL the modules are on the black list. 1906 if (num_modules > 0) { 1907 for (size_t i = 0; i < num_modules; i++) { 1908 if (!ModuleIsExcludedForUnconstrainedSearches( 1909 matchingModules.GetModuleAtIndex(i))) 1910 return false; 1911 } 1912 return true; 1913 } 1914 } 1915 return false; 1916 } 1917 1918 bool Target::ModuleIsExcludedForUnconstrainedSearches( 1919 const lldb::ModuleSP &module_sp) { 1920 if (GetBreakpointsConsultPlatformAvoidList()) { 1921 if (m_platform_sp) 1922 return m_platform_sp->ModuleIsExcludedForUnconstrainedSearches(*this, 1923 module_sp); 1924 } 1925 return false; 1926 } 1927 1928 size_t Target::ReadMemoryFromFileCache(const Address &addr, void *dst, 1929 size_t dst_len, Status &error) { 1930 SectionSP section_sp(addr.GetSection()); 1931 if (section_sp) { 1932 // If the contents of this section are encrypted, the on-disk file is 1933 // unusable. Read only from live memory. 1934 if (section_sp->IsEncrypted()) { 1935 error = Status::FromErrorString("section is encrypted"); 1936 return 0; 1937 } 1938 ModuleSP module_sp(section_sp->GetModule()); 1939 if (module_sp) { 1940 ObjectFile *objfile = section_sp->GetModule()->GetObjectFile(); 1941 if (objfile) { 1942 size_t bytes_read = objfile->ReadSectionData( 1943 section_sp.get(), addr.GetOffset(), dst, dst_len); 1944 if (bytes_read > 0) 1945 return bytes_read; 1946 else 1947 error = Status::FromErrorStringWithFormat( 1948 "error reading data from section %s", 1949 section_sp->GetName().GetCString()); 1950 } else 1951 error = Status::FromErrorString("address isn't from a object file"); 1952 } else 1953 error = Status::FromErrorString("address isn't in a module"); 1954 } else 1955 error = Status::FromErrorString( 1956 "address doesn't contain a section that points to a " 1957 "section in a object file"); 1958 1959 return 0; 1960 } 1961 1962 size_t Target::ReadMemory(const Address &addr, void *dst, size_t dst_len, 1963 Status &error, bool force_live_memory, 1964 lldb::addr_t *load_addr_ptr) { 1965 error.Clear(); 1966 1967 Address fixed_addr = addr; 1968 if (ProcessIsValid()) 1969 if (const ABISP &abi = m_process_sp->GetABI()) 1970 fixed_addr.SetLoadAddress(abi->FixAnyAddress(addr.GetLoadAddress(this)), 1971 this); 1972 1973 // if we end up reading this from process memory, we will fill this with the 1974 // actual load address 1975 if (load_addr_ptr) 1976 *load_addr_ptr = LLDB_INVALID_ADDRESS; 1977 1978 size_t bytes_read = 0; 1979 1980 addr_t load_addr = LLDB_INVALID_ADDRESS; 1981 addr_t file_addr = LLDB_INVALID_ADDRESS; 1982 Address resolved_addr; 1983 if (!fixed_addr.IsSectionOffset()) { 1984 SectionLoadList §ion_load_list = GetSectionLoadList(); 1985 if (section_load_list.IsEmpty()) { 1986 // No sections are loaded, so we must assume we are not running yet and 1987 // anything we are given is a file address. 1988 file_addr = 1989 fixed_addr.GetOffset(); // "fixed_addr" doesn't have a section, so 1990 // its offset is the file address 1991 m_images.ResolveFileAddress(file_addr, resolved_addr); 1992 } else { 1993 // We have at least one section loaded. This can be because we have 1994 // manually loaded some sections with "target modules load ..." or 1995 // because we have a live process that has sections loaded through 1996 // the dynamic loader 1997 load_addr = 1998 fixed_addr.GetOffset(); // "fixed_addr" doesn't have a section, so 1999 // its offset is the load address 2000 section_load_list.ResolveLoadAddress(load_addr, resolved_addr); 2001 } 2002 } 2003 if (!resolved_addr.IsValid()) 2004 resolved_addr = fixed_addr; 2005 2006 // If we read from the file cache but can't get as many bytes as requested, 2007 // we keep the result around in this buffer, in case this result is the 2008 // best we can do. 2009 std::unique_ptr<uint8_t[]> file_cache_read_buffer; 2010 size_t file_cache_bytes_read = 0; 2011 2012 // Read from file cache if read-only section. 2013 if (!force_live_memory && resolved_addr.IsSectionOffset()) { 2014 SectionSP section_sp(resolved_addr.GetSection()); 2015 if (section_sp) { 2016 auto permissions = Flags(section_sp->GetPermissions()); 2017 bool is_readonly = !permissions.Test(ePermissionsWritable) && 2018 permissions.Test(ePermissionsReadable); 2019 if (is_readonly) { 2020 file_cache_bytes_read = 2021 ReadMemoryFromFileCache(resolved_addr, dst, dst_len, error); 2022 if (file_cache_bytes_read == dst_len) 2023 return file_cache_bytes_read; 2024 else if (file_cache_bytes_read > 0) { 2025 file_cache_read_buffer = 2026 std::make_unique<uint8_t[]>(file_cache_bytes_read); 2027 std::memcpy(file_cache_read_buffer.get(), dst, file_cache_bytes_read); 2028 } 2029 } 2030 } 2031 } 2032 2033 if (ProcessIsValid()) { 2034 if (load_addr == LLDB_INVALID_ADDRESS) 2035 load_addr = resolved_addr.GetLoadAddress(this); 2036 2037 if (load_addr == LLDB_INVALID_ADDRESS) { 2038 ModuleSP addr_module_sp(resolved_addr.GetModule()); 2039 if (addr_module_sp && addr_module_sp->GetFileSpec()) 2040 error = Status::FromErrorStringWithFormatv( 2041 "{0:F}[{1:x+}] can't be resolved, {0:F} is not currently loaded", 2042 addr_module_sp->GetFileSpec(), resolved_addr.GetFileAddress()); 2043 else 2044 error = Status::FromErrorStringWithFormat( 2045 "0x%" PRIx64 " can't be resolved", resolved_addr.GetFileAddress()); 2046 } else { 2047 bytes_read = m_process_sp->ReadMemory(load_addr, dst, dst_len, error); 2048 if (bytes_read != dst_len) { 2049 if (error.Success()) { 2050 if (bytes_read == 0) 2051 error = Status::FromErrorStringWithFormat( 2052 "read memory from 0x%" PRIx64 " failed", load_addr); 2053 else 2054 error = Status::FromErrorStringWithFormat( 2055 "only %" PRIu64 " of %" PRIu64 2056 " bytes were read from memory at 0x%" PRIx64, 2057 (uint64_t)bytes_read, (uint64_t)dst_len, load_addr); 2058 } 2059 } 2060 if (bytes_read) { 2061 if (load_addr_ptr) 2062 *load_addr_ptr = load_addr; 2063 return bytes_read; 2064 } 2065 } 2066 } 2067 2068 if (file_cache_read_buffer && file_cache_bytes_read > 0) { 2069 // Reading from the process failed. If we've previously succeeded in reading 2070 // something from the file cache, then copy that over and return that. 2071 std::memcpy(dst, file_cache_read_buffer.get(), file_cache_bytes_read); 2072 return file_cache_bytes_read; 2073 } 2074 2075 if (!file_cache_read_buffer && resolved_addr.IsSectionOffset()) { 2076 // If we didn't already try and read from the object file cache, then try 2077 // it after failing to read from the process. 2078 return ReadMemoryFromFileCache(resolved_addr, dst, dst_len, error); 2079 } 2080 return 0; 2081 } 2082 2083 size_t Target::ReadCStringFromMemory(const Address &addr, std::string &out_str, 2084 Status &error, bool force_live_memory) { 2085 char buf[256]; 2086 out_str.clear(); 2087 addr_t curr_addr = addr.GetLoadAddress(this); 2088 Address address(addr); 2089 while (true) { 2090 size_t length = ReadCStringFromMemory(address, buf, sizeof(buf), error, 2091 force_live_memory); 2092 if (length == 0) 2093 break; 2094 out_str.append(buf, length); 2095 // If we got "length - 1" bytes, we didn't get the whole C string, we need 2096 // to read some more characters 2097 if (length == sizeof(buf) - 1) 2098 curr_addr += length; 2099 else 2100 break; 2101 address = Address(curr_addr); 2102 } 2103 return out_str.size(); 2104 } 2105 2106 size_t Target::ReadCStringFromMemory(const Address &addr, char *dst, 2107 size_t dst_max_len, Status &result_error, 2108 bool force_live_memory) { 2109 size_t total_cstr_len = 0; 2110 if (dst && dst_max_len) { 2111 result_error.Clear(); 2112 // NULL out everything just to be safe 2113 memset(dst, 0, dst_max_len); 2114 addr_t curr_addr = addr.GetLoadAddress(this); 2115 Address address(addr); 2116 2117 // We could call m_process_sp->GetMemoryCacheLineSize() but I don't think 2118 // this really needs to be tied to the memory cache subsystem's cache line 2119 // size, so leave this as a fixed constant. 2120 const size_t cache_line_size = 512; 2121 2122 size_t bytes_left = dst_max_len - 1; 2123 char *curr_dst = dst; 2124 2125 while (bytes_left > 0) { 2126 addr_t cache_line_bytes_left = 2127 cache_line_size - (curr_addr % cache_line_size); 2128 addr_t bytes_to_read = 2129 std::min<addr_t>(bytes_left, cache_line_bytes_left); 2130 Status error; 2131 size_t bytes_read = ReadMemory(address, curr_dst, bytes_to_read, error, 2132 force_live_memory); 2133 2134 if (bytes_read == 0) { 2135 result_error = std::move(error); 2136 dst[total_cstr_len] = '\0'; 2137 break; 2138 } 2139 const size_t len = strlen(curr_dst); 2140 2141 total_cstr_len += len; 2142 2143 if (len < bytes_to_read) 2144 break; 2145 2146 curr_dst += bytes_read; 2147 curr_addr += bytes_read; 2148 bytes_left -= bytes_read; 2149 address = Address(curr_addr); 2150 } 2151 } else { 2152 if (dst == nullptr) 2153 result_error = Status::FromErrorString("invalid arguments"); 2154 else 2155 result_error.Clear(); 2156 } 2157 return total_cstr_len; 2158 } 2159 2160 addr_t Target::GetReasonableReadSize(const Address &addr) { 2161 addr_t load_addr = addr.GetLoadAddress(this); 2162 if (load_addr != LLDB_INVALID_ADDRESS && m_process_sp) { 2163 // Avoid crossing cache line boundaries. 2164 addr_t cache_line_size = m_process_sp->GetMemoryCacheLineSize(); 2165 return cache_line_size - (load_addr % cache_line_size); 2166 } 2167 2168 // The read is going to go to the file cache, so we can just pick a largish 2169 // value. 2170 return 0x1000; 2171 } 2172 2173 size_t Target::ReadStringFromMemory(const Address &addr, char *dst, 2174 size_t max_bytes, Status &error, 2175 size_t type_width, bool force_live_memory) { 2176 if (!dst || !max_bytes || !type_width || max_bytes < type_width) 2177 return 0; 2178 2179 size_t total_bytes_read = 0; 2180 2181 // Ensure a null terminator independent of the number of bytes that is 2182 // read. 2183 memset(dst, 0, max_bytes); 2184 size_t bytes_left = max_bytes - type_width; 2185 2186 const char terminator[4] = {'\0', '\0', '\0', '\0'}; 2187 assert(sizeof(terminator) >= type_width && "Attempting to validate a " 2188 "string with more than 4 bytes " 2189 "per character!"); 2190 2191 Address address = addr; 2192 char *curr_dst = dst; 2193 2194 error.Clear(); 2195 while (bytes_left > 0 && error.Success()) { 2196 addr_t bytes_to_read = 2197 std::min<addr_t>(bytes_left, GetReasonableReadSize(address)); 2198 size_t bytes_read = 2199 ReadMemory(address, curr_dst, bytes_to_read, error, force_live_memory); 2200 2201 if (bytes_read == 0) 2202 break; 2203 2204 // Search for a null terminator of correct size and alignment in 2205 // bytes_read 2206 size_t aligned_start = total_bytes_read - total_bytes_read % type_width; 2207 for (size_t i = aligned_start; 2208 i + type_width <= total_bytes_read + bytes_read; i += type_width) 2209 if (::memcmp(&dst[i], terminator, type_width) == 0) { 2210 error.Clear(); 2211 return i; 2212 } 2213 2214 total_bytes_read += bytes_read; 2215 curr_dst += bytes_read; 2216 address.Slide(bytes_read); 2217 bytes_left -= bytes_read; 2218 } 2219 return total_bytes_read; 2220 } 2221 2222 size_t Target::ReadScalarIntegerFromMemory(const Address &addr, uint32_t byte_size, 2223 bool is_signed, Scalar &scalar, 2224 Status &error, 2225 bool force_live_memory) { 2226 uint64_t uval; 2227 2228 if (byte_size <= sizeof(uval)) { 2229 size_t bytes_read = 2230 ReadMemory(addr, &uval, byte_size, error, force_live_memory); 2231 if (bytes_read == byte_size) { 2232 DataExtractor data(&uval, sizeof(uval), m_arch.GetSpec().GetByteOrder(), 2233 m_arch.GetSpec().GetAddressByteSize()); 2234 lldb::offset_t offset = 0; 2235 if (byte_size <= 4) 2236 scalar = data.GetMaxU32(&offset, byte_size); 2237 else 2238 scalar = data.GetMaxU64(&offset, byte_size); 2239 2240 if (is_signed) 2241 scalar.SignExtend(byte_size * 8); 2242 return bytes_read; 2243 } 2244 } else { 2245 error = Status::FromErrorStringWithFormat( 2246 "byte size of %u is too large for integer scalar type", byte_size); 2247 } 2248 return 0; 2249 } 2250 2251 uint64_t Target::ReadUnsignedIntegerFromMemory(const Address &addr, 2252 size_t integer_byte_size, 2253 uint64_t fail_value, Status &error, 2254 bool force_live_memory) { 2255 Scalar scalar; 2256 if (ReadScalarIntegerFromMemory(addr, integer_byte_size, false, scalar, error, 2257 force_live_memory)) 2258 return scalar.ULongLong(fail_value); 2259 return fail_value; 2260 } 2261 2262 bool Target::ReadPointerFromMemory(const Address &addr, Status &error, 2263 Address &pointer_addr, 2264 bool force_live_memory) { 2265 Scalar scalar; 2266 if (ReadScalarIntegerFromMemory(addr, m_arch.GetSpec().GetAddressByteSize(), 2267 false, scalar, error, force_live_memory)) { 2268 addr_t pointer_vm_addr = scalar.ULongLong(LLDB_INVALID_ADDRESS); 2269 if (pointer_vm_addr != LLDB_INVALID_ADDRESS) { 2270 SectionLoadList §ion_load_list = GetSectionLoadList(); 2271 if (section_load_list.IsEmpty()) { 2272 // No sections are loaded, so we must assume we are not running yet and 2273 // anything we are given is a file address. 2274 m_images.ResolveFileAddress(pointer_vm_addr, pointer_addr); 2275 } else { 2276 // We have at least one section loaded. This can be because we have 2277 // manually loaded some sections with "target modules load ..." or 2278 // because we have a live process that has sections loaded through 2279 // the dynamic loader 2280 section_load_list.ResolveLoadAddress(pointer_vm_addr, pointer_addr); 2281 } 2282 // We weren't able to resolve the pointer value, so just return an 2283 // address with no section 2284 if (!pointer_addr.IsValid()) 2285 pointer_addr.SetOffset(pointer_vm_addr); 2286 return true; 2287 } 2288 } 2289 return false; 2290 } 2291 2292 ModuleSP Target::GetOrCreateModule(const ModuleSpec &orig_module_spec, 2293 bool notify, Status *error_ptr) { 2294 ModuleSP module_sp; 2295 2296 Status error; 2297 2298 // Apply any remappings specified in target.object-map: 2299 ModuleSpec module_spec(orig_module_spec); 2300 PathMappingList &obj_mapping = GetObjectPathMap(); 2301 if (std::optional<FileSpec> remapped_obj_file = 2302 obj_mapping.RemapPath(orig_module_spec.GetFileSpec().GetPath(), 2303 true /* only_if_exists */)) { 2304 module_spec.GetFileSpec().SetPath(remapped_obj_file->GetPath()); 2305 } 2306 2307 // First see if we already have this module in our module list. If we do, 2308 // then we're done, we don't need to consult the shared modules list. But 2309 // only do this if we are passed a UUID. 2310 2311 if (module_spec.GetUUID().IsValid()) 2312 module_sp = m_images.FindFirstModule(module_spec); 2313 2314 if (!module_sp) { 2315 llvm::SmallVector<ModuleSP, 1> 2316 old_modules; // This will get filled in if we have a new version 2317 // of the library 2318 bool did_create_module = false; 2319 FileSpecList search_paths = GetExecutableSearchPaths(); 2320 FileSpec symbol_file_spec; 2321 2322 // Call locate module callback if set. This allows users to implement their 2323 // own module cache system. For example, to leverage build system artifacts, 2324 // to bypass pulling files from remote platform, or to search symbol files 2325 // from symbol servers. 2326 if (m_platform_sp) 2327 m_platform_sp->CallLocateModuleCallbackIfSet( 2328 module_spec, module_sp, symbol_file_spec, &did_create_module); 2329 2330 // The result of this CallLocateModuleCallbackIfSet is one of the following. 2331 // 1. module_sp:loaded, symbol_file_spec:set 2332 // The callback found a module file and a symbol file for the 2333 // module_spec. We will call module_sp->SetSymbolFileFileSpec with 2334 // the symbol_file_spec later. 2335 // 2. module_sp:loaded, symbol_file_spec:empty 2336 // The callback only found a module file for the module_spec. 2337 // 3. module_sp:empty, symbol_file_spec:set 2338 // The callback only found a symbol file for the module. We continue 2339 // to find a module file for this module_spec and we will call 2340 // module_sp->SetSymbolFileFileSpec with the symbol_file_spec later. 2341 // 4. module_sp:empty, symbol_file_spec:empty 2342 // Platform does not exist, the callback is not set, the callback did 2343 // not find any module files nor any symbol files, the callback failed, 2344 // or something went wrong. We continue to find a module file for this 2345 // module_spec. 2346 2347 if (!module_sp) { 2348 // If there are image search path entries, try to use them to acquire a 2349 // suitable image. 2350 if (m_image_search_paths.GetSize()) { 2351 ModuleSpec transformed_spec(module_spec); 2352 ConstString transformed_dir; 2353 if (m_image_search_paths.RemapPath( 2354 module_spec.GetFileSpec().GetDirectory(), transformed_dir)) { 2355 transformed_spec.GetFileSpec().SetDirectory(transformed_dir); 2356 transformed_spec.GetFileSpec().SetFilename( 2357 module_spec.GetFileSpec().GetFilename()); 2358 error = ModuleList::GetSharedModule(transformed_spec, module_sp, 2359 &search_paths, &old_modules, 2360 &did_create_module); 2361 } 2362 } 2363 } 2364 2365 if (!module_sp) { 2366 // If we have a UUID, we can check our global shared module list in case 2367 // we already have it. If we don't have a valid UUID, then we can't since 2368 // the path in "module_spec" will be a platform path, and we will need to 2369 // let the platform find that file. For example, we could be asking for 2370 // "/usr/lib/dyld" and if we do not have a UUID, we don't want to pick 2371 // the local copy of "/usr/lib/dyld" since our platform could be a remote 2372 // platform that has its own "/usr/lib/dyld" in an SDK or in a local file 2373 // cache. 2374 if (module_spec.GetUUID().IsValid()) { 2375 // We have a UUID, it is OK to check the global module list... 2376 error = 2377 ModuleList::GetSharedModule(module_spec, module_sp, &search_paths, 2378 &old_modules, &did_create_module); 2379 } 2380 2381 if (!module_sp) { 2382 // The platform is responsible for finding and caching an appropriate 2383 // module in the shared module cache. 2384 if (m_platform_sp) { 2385 error = m_platform_sp->GetSharedModule( 2386 module_spec, m_process_sp.get(), module_sp, &search_paths, 2387 &old_modules, &did_create_module); 2388 } else { 2389 error = Status::FromErrorString("no platform is currently set"); 2390 } 2391 } 2392 } 2393 2394 // We found a module that wasn't in our target list. Let's make sure that 2395 // there wasn't an equivalent module in the list already, and if there was, 2396 // let's remove it. 2397 if (module_sp) { 2398 ObjectFile *objfile = module_sp->GetObjectFile(); 2399 if (objfile) { 2400 switch (objfile->GetType()) { 2401 case ObjectFile::eTypeCoreFile: /// A core file that has a checkpoint of 2402 /// a program's execution state 2403 case ObjectFile::eTypeExecutable: /// A normal executable 2404 case ObjectFile::eTypeDynamicLinker: /// The platform's dynamic linker 2405 /// executable 2406 case ObjectFile::eTypeObjectFile: /// An intermediate object file 2407 case ObjectFile::eTypeSharedLibrary: /// A shared library that can be 2408 /// used during execution 2409 break; 2410 case ObjectFile::eTypeDebugInfo: /// An object file that contains only 2411 /// debug information 2412 if (error_ptr) 2413 *error_ptr = Status::FromErrorString( 2414 "debug info files aren't valid target " 2415 "modules, please specify an executable"); 2416 return ModuleSP(); 2417 case ObjectFile::eTypeStubLibrary: /// A library that can be linked 2418 /// against but not used for 2419 /// execution 2420 if (error_ptr) 2421 *error_ptr = Status::FromErrorString( 2422 "stub libraries aren't valid target " 2423 "modules, please specify an executable"); 2424 return ModuleSP(); 2425 default: 2426 if (error_ptr) 2427 *error_ptr = Status::FromErrorString( 2428 "unsupported file type, please specify an executable"); 2429 return ModuleSP(); 2430 } 2431 // GetSharedModule is not guaranteed to find the old shared module, for 2432 // instance in the common case where you pass in the UUID, it is only 2433 // going to find the one module matching the UUID. In fact, it has no 2434 // good way to know what the "old module" relevant to this target is, 2435 // since there might be many copies of a module with this file spec in 2436 // various running debug sessions, but only one of them will belong to 2437 // this target. So let's remove the UUID from the module list, and look 2438 // in the target's module list. Only do this if there is SOMETHING else 2439 // in the module spec... 2440 if (module_spec.GetUUID().IsValid() && 2441 !module_spec.GetFileSpec().GetFilename().IsEmpty() && 2442 !module_spec.GetFileSpec().GetDirectory().IsEmpty()) { 2443 ModuleSpec module_spec_copy(module_spec.GetFileSpec()); 2444 module_spec_copy.GetUUID().Clear(); 2445 2446 ModuleList found_modules; 2447 m_images.FindModules(module_spec_copy, found_modules); 2448 found_modules.ForEach([&](const ModuleSP &found_module) -> bool { 2449 old_modules.push_back(found_module); 2450 return true; 2451 }); 2452 } 2453 2454 // If the locate module callback had found a symbol file, set it to the 2455 // module_sp before preloading symbols. 2456 if (symbol_file_spec) 2457 module_sp->SetSymbolFileFileSpec(symbol_file_spec); 2458 2459 // Preload symbols outside of any lock, so hopefully we can do this for 2460 // each library in parallel. 2461 if (GetPreloadSymbols()) 2462 module_sp->PreloadSymbols(); 2463 llvm::SmallVector<ModuleSP, 1> replaced_modules; 2464 for (ModuleSP &old_module_sp : old_modules) { 2465 if (m_images.GetIndexForModule(old_module_sp.get()) != 2466 LLDB_INVALID_INDEX32) { 2467 if (replaced_modules.empty()) 2468 m_images.ReplaceModule(old_module_sp, module_sp); 2469 else 2470 m_images.Remove(old_module_sp); 2471 2472 replaced_modules.push_back(std::move(old_module_sp)); 2473 } 2474 } 2475 2476 if (replaced_modules.size() > 1) { 2477 // The same new module replaced multiple old modules 2478 // simultaneously. It's not clear this should ever 2479 // happen (if we always replace old modules as we add 2480 // new ones, presumably we should never have more than 2481 // one old one). If there are legitimate cases where 2482 // this happens, then the ModuleList::Notifier interface 2483 // may need to be adjusted to allow reporting this. 2484 // In the meantime, just log that this has happened; just 2485 // above we called ReplaceModule on the first one, and Remove 2486 // on the rest. 2487 if (Log *log = GetLog(LLDBLog::Target | LLDBLog::Modules)) { 2488 StreamString message; 2489 auto dump = [&message](Module &dump_module) -> void { 2490 UUID dump_uuid = dump_module.GetUUID(); 2491 2492 message << '['; 2493 dump_module.GetDescription(message.AsRawOstream()); 2494 message << " (uuid "; 2495 2496 if (dump_uuid.IsValid()) 2497 dump_uuid.Dump(message); 2498 else 2499 message << "not specified"; 2500 2501 message << ")]"; 2502 }; 2503 2504 message << "New module "; 2505 dump(*module_sp); 2506 message.AsRawOstream() 2507 << llvm::formatv(" simultaneously replaced {0} old modules: ", 2508 replaced_modules.size()); 2509 for (ModuleSP &replaced_module_sp : replaced_modules) 2510 dump(*replaced_module_sp); 2511 2512 log->PutString(message.GetString()); 2513 } 2514 } 2515 2516 if (replaced_modules.empty()) 2517 m_images.Append(module_sp, notify); 2518 2519 for (ModuleSP &old_module_sp : replaced_modules) { 2520 Module *old_module_ptr = old_module_sp.get(); 2521 old_module_sp.reset(); 2522 ModuleList::RemoveSharedModuleIfOrphaned(old_module_ptr); 2523 } 2524 } else 2525 module_sp.reset(); 2526 } 2527 } 2528 if (error_ptr) 2529 *error_ptr = std::move(error); 2530 return module_sp; 2531 } 2532 2533 TargetSP Target::CalculateTarget() { return shared_from_this(); } 2534 2535 ProcessSP Target::CalculateProcess() { return m_process_sp; } 2536 2537 ThreadSP Target::CalculateThread() { return ThreadSP(); } 2538 2539 StackFrameSP Target::CalculateStackFrame() { return StackFrameSP(); } 2540 2541 void Target::CalculateExecutionContext(ExecutionContext &exe_ctx) { 2542 exe_ctx.Clear(); 2543 exe_ctx.SetTargetPtr(this); 2544 } 2545 2546 PathMappingList &Target::GetImageSearchPathList() { 2547 return m_image_search_paths; 2548 } 2549 2550 void Target::ImageSearchPathsChanged(const PathMappingList &path_list, 2551 void *baton) { 2552 Target *target = (Target *)baton; 2553 ModuleSP exe_module_sp(target->GetExecutableModule()); 2554 if (exe_module_sp) 2555 target->SetExecutableModule(exe_module_sp, eLoadDependentsYes); 2556 } 2557 2558 llvm::Expected<lldb::TypeSystemSP> 2559 Target::GetScratchTypeSystemForLanguage(lldb::LanguageType language, 2560 bool create_on_demand) { 2561 if (!m_valid) 2562 return llvm::createStringError("Invalid Target"); 2563 2564 if (language == eLanguageTypeMipsAssembler // GNU AS and LLVM use it for all 2565 // assembly code 2566 || language == eLanguageTypeUnknown) { 2567 LanguageSet languages_for_expressions = 2568 Language::GetLanguagesSupportingTypeSystemsForExpressions(); 2569 2570 if (languages_for_expressions[eLanguageTypeC]) { 2571 language = eLanguageTypeC; // LLDB's default. Override by setting the 2572 // target language. 2573 } else { 2574 if (languages_for_expressions.Empty()) 2575 return llvm::createStringError( 2576 "No expression support for any languages"); 2577 language = (LanguageType)languages_for_expressions.bitvector.find_first(); 2578 } 2579 } 2580 2581 return m_scratch_type_system_map.GetTypeSystemForLanguage(language, this, 2582 create_on_demand); 2583 } 2584 2585 CompilerType Target::GetRegisterType(const std::string &name, 2586 const lldb_private::RegisterFlags &flags, 2587 uint32_t byte_size) { 2588 RegisterTypeBuilderSP provider = PluginManager::GetRegisterTypeBuilder(*this); 2589 assert(provider); 2590 return provider->GetRegisterType(name, flags, byte_size); 2591 } 2592 2593 std::vector<lldb::TypeSystemSP> 2594 Target::GetScratchTypeSystems(bool create_on_demand) { 2595 if (!m_valid) 2596 return {}; 2597 2598 // Some TypeSystem instances are associated with several LanguageTypes so 2599 // they will show up several times in the loop below. The SetVector filters 2600 // out all duplicates as they serve no use for the caller. 2601 std::vector<lldb::TypeSystemSP> scratch_type_systems; 2602 2603 LanguageSet languages_for_expressions = 2604 Language::GetLanguagesSupportingTypeSystemsForExpressions(); 2605 2606 for (auto bit : languages_for_expressions.bitvector.set_bits()) { 2607 auto language = (LanguageType)bit; 2608 auto type_system_or_err = 2609 GetScratchTypeSystemForLanguage(language, create_on_demand); 2610 if (!type_system_or_err) 2611 LLDB_LOG_ERROR( 2612 GetLog(LLDBLog::Target), type_system_or_err.takeError(), 2613 "Language '{1}' has expression support but no scratch type " 2614 "system available: {0}", 2615 Language::GetNameForLanguageType(language)); 2616 else 2617 if (auto ts = *type_system_or_err) 2618 scratch_type_systems.push_back(ts); 2619 } 2620 2621 std::sort(scratch_type_systems.begin(), scratch_type_systems.end()); 2622 scratch_type_systems.erase( 2623 std::unique(scratch_type_systems.begin(), scratch_type_systems.end()), 2624 scratch_type_systems.end()); 2625 return scratch_type_systems; 2626 } 2627 2628 PersistentExpressionState * 2629 Target::GetPersistentExpressionStateForLanguage(lldb::LanguageType language) { 2630 auto type_system_or_err = GetScratchTypeSystemForLanguage(language, true); 2631 2632 if (auto err = type_system_or_err.takeError()) { 2633 LLDB_LOG_ERROR( 2634 GetLog(LLDBLog::Target), std::move(err), 2635 "Unable to get persistent expression state for language {1}: {0}", 2636 Language::GetNameForLanguageType(language)); 2637 return nullptr; 2638 } 2639 2640 if (auto ts = *type_system_or_err) 2641 return ts->GetPersistentExpressionState(); 2642 2643 LLDB_LOG(GetLog(LLDBLog::Target), 2644 "Unable to get persistent expression state for language {1}: {0}", 2645 Language::GetNameForLanguageType(language)); 2646 return nullptr; 2647 } 2648 2649 UserExpression *Target::GetUserExpressionForLanguage( 2650 llvm::StringRef expr, llvm::StringRef prefix, SourceLanguage language, 2651 Expression::ResultType desired_type, 2652 const EvaluateExpressionOptions &options, ValueObject *ctx_obj, 2653 Status &error) { 2654 auto type_system_or_err = 2655 GetScratchTypeSystemForLanguage(language.AsLanguageType()); 2656 if (auto err = type_system_or_err.takeError()) { 2657 error = Status::FromErrorStringWithFormat( 2658 "Could not find type system for language %s: %s", 2659 Language::GetNameForLanguageType(language.AsLanguageType()), 2660 llvm::toString(std::move(err)).c_str()); 2661 return nullptr; 2662 } 2663 2664 auto ts = *type_system_or_err; 2665 if (!ts) { 2666 error = Status::FromErrorStringWithFormat( 2667 "Type system for language %s is no longer live", 2668 language.GetDescription().data()); 2669 return nullptr; 2670 } 2671 2672 auto *user_expr = ts->GetUserExpression(expr, prefix, language, desired_type, 2673 options, ctx_obj); 2674 if (!user_expr) 2675 error = Status::FromErrorStringWithFormat( 2676 "Could not create an expression for language %s", 2677 language.GetDescription().data()); 2678 2679 return user_expr; 2680 } 2681 2682 FunctionCaller *Target::GetFunctionCallerForLanguage( 2683 lldb::LanguageType language, const CompilerType &return_type, 2684 const Address &function_address, const ValueList &arg_value_list, 2685 const char *name, Status &error) { 2686 auto type_system_or_err = GetScratchTypeSystemForLanguage(language); 2687 if (auto err = type_system_or_err.takeError()) { 2688 error = Status::FromErrorStringWithFormat( 2689 "Could not find type system for language %s: %s", 2690 Language::GetNameForLanguageType(language), 2691 llvm::toString(std::move(err)).c_str()); 2692 return nullptr; 2693 } 2694 auto ts = *type_system_or_err; 2695 if (!ts) { 2696 error = Status::FromErrorStringWithFormat( 2697 "Type system for language %s is no longer live", 2698 Language::GetNameForLanguageType(language)); 2699 return nullptr; 2700 } 2701 auto *persistent_fn = ts->GetFunctionCaller(return_type, function_address, 2702 arg_value_list, name); 2703 if (!persistent_fn) 2704 error = Status::FromErrorStringWithFormat( 2705 "Could not create an expression for language %s", 2706 Language::GetNameForLanguageType(language)); 2707 2708 return persistent_fn; 2709 } 2710 2711 llvm::Expected<std::unique_ptr<UtilityFunction>> 2712 Target::CreateUtilityFunction(std::string expression, std::string name, 2713 lldb::LanguageType language, 2714 ExecutionContext &exe_ctx) { 2715 auto type_system_or_err = GetScratchTypeSystemForLanguage(language); 2716 if (!type_system_or_err) 2717 return type_system_or_err.takeError(); 2718 auto ts = *type_system_or_err; 2719 if (!ts) 2720 return llvm::createStringError( 2721 llvm::StringRef("Type system for language ") + 2722 Language::GetNameForLanguageType(language) + 2723 llvm::StringRef(" is no longer live")); 2724 std::unique_ptr<UtilityFunction> utility_fn = 2725 ts->CreateUtilityFunction(std::move(expression), std::move(name)); 2726 if (!utility_fn) 2727 return llvm::createStringError( 2728 llvm::StringRef("Could not create an expression for language") + 2729 Language::GetNameForLanguageType(language)); 2730 2731 DiagnosticManager diagnostics; 2732 if (!utility_fn->Install(diagnostics, exe_ctx)) 2733 return diagnostics.GetAsError(lldb::eExpressionSetupError, 2734 "Could not install utility function:"); 2735 2736 return std::move(utility_fn); 2737 } 2738 2739 void Target::SettingsInitialize() { Process::SettingsInitialize(); } 2740 2741 void Target::SettingsTerminate() { Process::SettingsTerminate(); } 2742 2743 FileSpecList Target::GetDefaultExecutableSearchPaths() { 2744 return Target::GetGlobalProperties().GetExecutableSearchPaths(); 2745 } 2746 2747 FileSpecList Target::GetDefaultDebugFileSearchPaths() { 2748 return Target::GetGlobalProperties().GetDebugFileSearchPaths(); 2749 } 2750 2751 ArchSpec Target::GetDefaultArchitecture() { 2752 return Target::GetGlobalProperties().GetDefaultArchitecture(); 2753 } 2754 2755 void Target::SetDefaultArchitecture(const ArchSpec &arch) { 2756 LLDB_LOG(GetLog(LLDBLog::Target), 2757 "setting target's default architecture to {0} ({1})", 2758 arch.GetArchitectureName(), arch.GetTriple().getTriple()); 2759 Target::GetGlobalProperties().SetDefaultArchitecture(arch); 2760 } 2761 2762 llvm::Error Target::SetLabel(llvm::StringRef label) { 2763 size_t n = LLDB_INVALID_INDEX32; 2764 if (llvm::to_integer(label, n)) 2765 return llvm::createStringError("Cannot use integer as target label."); 2766 TargetList &targets = GetDebugger().GetTargetList(); 2767 for (size_t i = 0; i < targets.GetNumTargets(); i++) { 2768 TargetSP target_sp = targets.GetTargetAtIndex(i); 2769 if (target_sp && target_sp->GetLabel() == label) { 2770 return llvm::make_error<llvm::StringError>( 2771 llvm::formatv( 2772 "Cannot use label '{0}' since it's set in target #{1}.", label, 2773 i), 2774 llvm::inconvertibleErrorCode()); 2775 } 2776 } 2777 2778 m_label = label.str(); 2779 return llvm::Error::success(); 2780 } 2781 2782 Target *Target::GetTargetFromContexts(const ExecutionContext *exe_ctx_ptr, 2783 const SymbolContext *sc_ptr) { 2784 // The target can either exist in the "process" of ExecutionContext, or in 2785 // the "target_sp" member of SymbolContext. This accessor helper function 2786 // will get the target from one of these locations. 2787 2788 Target *target = nullptr; 2789 if (sc_ptr != nullptr) 2790 target = sc_ptr->target_sp.get(); 2791 if (target == nullptr && exe_ctx_ptr) 2792 target = exe_ctx_ptr->GetTargetPtr(); 2793 return target; 2794 } 2795 2796 ExpressionResults Target::EvaluateExpression( 2797 llvm::StringRef expr, ExecutionContextScope *exe_scope, 2798 lldb::ValueObjectSP &result_valobj_sp, 2799 const EvaluateExpressionOptions &options, std::string *fixed_expression, 2800 ValueObject *ctx_obj) { 2801 result_valobj_sp.reset(); 2802 2803 ExpressionResults execution_results = eExpressionSetupError; 2804 2805 if (expr.empty()) { 2806 m_stats.GetExpressionStats().NotifyFailure(); 2807 return execution_results; 2808 } 2809 2810 // We shouldn't run stop hooks in expressions. 2811 bool old_suppress_value = m_suppress_stop_hooks; 2812 m_suppress_stop_hooks = true; 2813 auto on_exit = llvm::make_scope_exit([this, old_suppress_value]() { 2814 m_suppress_stop_hooks = old_suppress_value; 2815 }); 2816 2817 ExecutionContext exe_ctx; 2818 2819 if (exe_scope) { 2820 exe_scope->CalculateExecutionContext(exe_ctx); 2821 } else if (m_process_sp) { 2822 m_process_sp->CalculateExecutionContext(exe_ctx); 2823 } else { 2824 CalculateExecutionContext(exe_ctx); 2825 } 2826 2827 // Make sure we aren't just trying to see the value of a persistent variable 2828 // (something like "$0") 2829 // Only check for persistent variables the expression starts with a '$' 2830 lldb::ExpressionVariableSP persistent_var_sp; 2831 if (expr[0] == '$') { 2832 auto type_system_or_err = 2833 GetScratchTypeSystemForLanguage(eLanguageTypeC); 2834 if (auto err = type_system_or_err.takeError()) { 2835 LLDB_LOG_ERROR(GetLog(LLDBLog::Target), std::move(err), 2836 "Unable to get scratch type system"); 2837 } else { 2838 auto ts = *type_system_or_err; 2839 if (!ts) 2840 LLDB_LOG_ERROR(GetLog(LLDBLog::Target), std::move(err), 2841 "Scratch type system is no longer live: {0}"); 2842 else 2843 persistent_var_sp = 2844 ts->GetPersistentExpressionState()->GetVariable(expr); 2845 } 2846 } 2847 if (persistent_var_sp) { 2848 result_valobj_sp = persistent_var_sp->GetValueObject(); 2849 execution_results = eExpressionCompleted; 2850 } else { 2851 llvm::StringRef prefix = GetExpressionPrefixContents(); 2852 execution_results = 2853 UserExpression::Evaluate(exe_ctx, options, expr, prefix, 2854 result_valobj_sp, fixed_expression, ctx_obj); 2855 } 2856 2857 if (execution_results == eExpressionCompleted) 2858 m_stats.GetExpressionStats().NotifySuccess(); 2859 else 2860 m_stats.GetExpressionStats().NotifyFailure(); 2861 return execution_results; 2862 } 2863 2864 lldb::ExpressionVariableSP Target::GetPersistentVariable(ConstString name) { 2865 lldb::ExpressionVariableSP variable_sp; 2866 m_scratch_type_system_map.ForEach( 2867 [name, &variable_sp](TypeSystemSP type_system) -> bool { 2868 auto ts = type_system.get(); 2869 if (!ts) 2870 return true; 2871 if (PersistentExpressionState *persistent_state = 2872 ts->GetPersistentExpressionState()) { 2873 variable_sp = persistent_state->GetVariable(name); 2874 2875 if (variable_sp) 2876 return false; // Stop iterating the ForEach 2877 } 2878 return true; // Keep iterating the ForEach 2879 }); 2880 return variable_sp; 2881 } 2882 2883 lldb::addr_t Target::GetPersistentSymbol(ConstString name) { 2884 lldb::addr_t address = LLDB_INVALID_ADDRESS; 2885 2886 m_scratch_type_system_map.ForEach( 2887 [name, &address](lldb::TypeSystemSP type_system) -> bool { 2888 auto ts = type_system.get(); 2889 if (!ts) 2890 return true; 2891 2892 if (PersistentExpressionState *persistent_state = 2893 ts->GetPersistentExpressionState()) { 2894 address = persistent_state->LookupSymbol(name); 2895 if (address != LLDB_INVALID_ADDRESS) 2896 return false; // Stop iterating the ForEach 2897 } 2898 return true; // Keep iterating the ForEach 2899 }); 2900 return address; 2901 } 2902 2903 llvm::Expected<lldb_private::Address> Target::GetEntryPointAddress() { 2904 Module *exe_module = GetExecutableModulePointer(); 2905 2906 // Try to find the entry point address in the primary executable. 2907 const bool has_primary_executable = exe_module && exe_module->GetObjectFile(); 2908 if (has_primary_executable) { 2909 Address entry_addr = exe_module->GetObjectFile()->GetEntryPointAddress(); 2910 if (entry_addr.IsValid()) 2911 return entry_addr; 2912 } 2913 2914 const ModuleList &modules = GetImages(); 2915 const size_t num_images = modules.GetSize(); 2916 for (size_t idx = 0; idx < num_images; ++idx) { 2917 ModuleSP module_sp(modules.GetModuleAtIndex(idx)); 2918 if (!module_sp || !module_sp->GetObjectFile()) 2919 continue; 2920 2921 Address entry_addr = module_sp->GetObjectFile()->GetEntryPointAddress(); 2922 if (entry_addr.IsValid()) 2923 return entry_addr; 2924 } 2925 2926 // We haven't found the entry point address. Return an appropriate error. 2927 if (!has_primary_executable) 2928 return llvm::createStringError( 2929 "No primary executable found and could not find entry point address in " 2930 "any executable module"); 2931 2932 return llvm::createStringError( 2933 "Could not find entry point address for primary executable module \"" + 2934 exe_module->GetFileSpec().GetFilename().GetStringRef() + "\""); 2935 } 2936 2937 lldb::addr_t Target::GetCallableLoadAddress(lldb::addr_t load_addr, 2938 AddressClass addr_class) const { 2939 auto arch_plugin = GetArchitecturePlugin(); 2940 return arch_plugin 2941 ? arch_plugin->GetCallableLoadAddress(load_addr, addr_class) 2942 : load_addr; 2943 } 2944 2945 lldb::addr_t Target::GetOpcodeLoadAddress(lldb::addr_t load_addr, 2946 AddressClass addr_class) const { 2947 auto arch_plugin = GetArchitecturePlugin(); 2948 return arch_plugin ? arch_plugin->GetOpcodeLoadAddress(load_addr, addr_class) 2949 : load_addr; 2950 } 2951 2952 lldb::addr_t Target::GetBreakableLoadAddress(lldb::addr_t addr) { 2953 auto arch_plugin = GetArchitecturePlugin(); 2954 return arch_plugin ? arch_plugin->GetBreakableLoadAddress(addr, *this) : addr; 2955 } 2956 2957 SourceManager &Target::GetSourceManager() { 2958 if (!m_source_manager_up) 2959 m_source_manager_up = std::make_unique<SourceManager>(shared_from_this()); 2960 return *m_source_manager_up; 2961 } 2962 2963 Target::StopHookSP Target::CreateStopHook(StopHook::StopHookKind kind) { 2964 lldb::user_id_t new_uid = ++m_stop_hook_next_id; 2965 Target::StopHookSP stop_hook_sp; 2966 switch (kind) { 2967 case StopHook::StopHookKind::CommandBased: 2968 stop_hook_sp.reset(new StopHookCommandLine(shared_from_this(), new_uid)); 2969 break; 2970 case StopHook::StopHookKind::ScriptBased: 2971 stop_hook_sp.reset(new StopHookScripted(shared_from_this(), new_uid)); 2972 break; 2973 } 2974 m_stop_hooks[new_uid] = stop_hook_sp; 2975 return stop_hook_sp; 2976 } 2977 2978 void Target::UndoCreateStopHook(lldb::user_id_t user_id) { 2979 if (!RemoveStopHookByID(user_id)) 2980 return; 2981 if (user_id == m_stop_hook_next_id) 2982 m_stop_hook_next_id--; 2983 } 2984 2985 bool Target::RemoveStopHookByID(lldb::user_id_t user_id) { 2986 size_t num_removed = m_stop_hooks.erase(user_id); 2987 return (num_removed != 0); 2988 } 2989 2990 void Target::RemoveAllStopHooks() { m_stop_hooks.clear(); } 2991 2992 Target::StopHookSP Target::GetStopHookByID(lldb::user_id_t user_id) { 2993 StopHookSP found_hook; 2994 2995 StopHookCollection::iterator specified_hook_iter; 2996 specified_hook_iter = m_stop_hooks.find(user_id); 2997 if (specified_hook_iter != m_stop_hooks.end()) 2998 found_hook = (*specified_hook_iter).second; 2999 return found_hook; 3000 } 3001 3002 bool Target::SetStopHookActiveStateByID(lldb::user_id_t user_id, 3003 bool active_state) { 3004 StopHookCollection::iterator specified_hook_iter; 3005 specified_hook_iter = m_stop_hooks.find(user_id); 3006 if (specified_hook_iter == m_stop_hooks.end()) 3007 return false; 3008 3009 (*specified_hook_iter).second->SetIsActive(active_state); 3010 return true; 3011 } 3012 3013 void Target::SetAllStopHooksActiveState(bool active_state) { 3014 StopHookCollection::iterator pos, end = m_stop_hooks.end(); 3015 for (pos = m_stop_hooks.begin(); pos != end; pos++) { 3016 (*pos).second->SetIsActive(active_state); 3017 } 3018 } 3019 3020 bool Target::RunStopHooks() { 3021 if (m_suppress_stop_hooks) 3022 return false; 3023 3024 if (!m_process_sp) 3025 return false; 3026 3027 // Somebody might have restarted the process: 3028 // Still return false, the return value is about US restarting the target. 3029 if (m_process_sp->GetState() != eStateStopped) 3030 return false; 3031 3032 if (m_stop_hooks.empty()) 3033 return false; 3034 3035 // If there aren't any active stop hooks, don't bother either. 3036 bool any_active_hooks = false; 3037 for (auto hook : m_stop_hooks) { 3038 if (hook.second->IsActive()) { 3039 any_active_hooks = true; 3040 break; 3041 } 3042 } 3043 if (!any_active_hooks) 3044 return false; 3045 3046 // Make sure we check that we are not stopped because of us running a user 3047 // expression since in that case we do not want to run the stop-hooks. Note, 3048 // you can't just check whether the last stop was for a User Expression, 3049 // because breakpoint commands get run before stop hooks, and one of them 3050 // might have run an expression. You have to ensure you run the stop hooks 3051 // once per natural stop. 3052 uint32_t last_natural_stop = m_process_sp->GetModIDRef().GetLastNaturalStopID(); 3053 if (last_natural_stop != 0 && m_latest_stop_hook_id == last_natural_stop) 3054 return false; 3055 3056 m_latest_stop_hook_id = last_natural_stop; 3057 3058 std::vector<ExecutionContext> exc_ctx_with_reasons; 3059 3060 ThreadList &cur_threadlist = m_process_sp->GetThreadList(); 3061 size_t num_threads = cur_threadlist.GetSize(); 3062 for (size_t i = 0; i < num_threads; i++) { 3063 lldb::ThreadSP cur_thread_sp = cur_threadlist.GetThreadAtIndex(i); 3064 if (cur_thread_sp->ThreadStoppedForAReason()) { 3065 lldb::StackFrameSP cur_frame_sp = cur_thread_sp->GetStackFrameAtIndex(0); 3066 exc_ctx_with_reasons.emplace_back(m_process_sp.get(), cur_thread_sp.get(), 3067 cur_frame_sp.get()); 3068 } 3069 } 3070 3071 // If no threads stopped for a reason, don't run the stop-hooks. 3072 size_t num_exe_ctx = exc_ctx_with_reasons.size(); 3073 if (num_exe_ctx == 0) 3074 return false; 3075 3076 StreamSP output_sp = m_debugger.GetAsyncOutputStream(); 3077 3078 bool auto_continue = false; 3079 bool hooks_ran = false; 3080 bool print_hook_header = (m_stop_hooks.size() != 1); 3081 bool print_thread_header = (num_exe_ctx != 1); 3082 bool should_stop = false; 3083 bool somebody_restarted = false; 3084 3085 for (auto stop_entry : m_stop_hooks) { 3086 StopHookSP cur_hook_sp = stop_entry.second; 3087 if (!cur_hook_sp->IsActive()) 3088 continue; 3089 3090 bool any_thread_matched = false; 3091 for (auto exc_ctx : exc_ctx_with_reasons) { 3092 // We detect somebody restarted in the stop-hook loop, and broke out of 3093 // that loop back to here. So break out of here too. 3094 if (somebody_restarted) 3095 break; 3096 3097 if (!cur_hook_sp->ExecutionContextPasses(exc_ctx)) 3098 continue; 3099 3100 // We only consult the auto-continue for a stop hook if it matched the 3101 // specifier. 3102 auto_continue |= cur_hook_sp->GetAutoContinue(); 3103 3104 if (!hooks_ran) 3105 hooks_ran = true; 3106 3107 if (print_hook_header && !any_thread_matched) { 3108 StreamString s; 3109 cur_hook_sp->GetDescription(s, eDescriptionLevelBrief); 3110 if (s.GetSize() != 0) 3111 output_sp->Printf("\n- Hook %" PRIu64 " (%s)\n", cur_hook_sp->GetID(), 3112 s.GetData()); 3113 else 3114 output_sp->Printf("\n- Hook %" PRIu64 "\n", cur_hook_sp->GetID()); 3115 any_thread_matched = true; 3116 } 3117 3118 if (print_thread_header) 3119 output_sp->Printf("-- Thread %d\n", 3120 exc_ctx.GetThreadPtr()->GetIndexID()); 3121 3122 StopHook::StopHookResult this_result = 3123 cur_hook_sp->HandleStop(exc_ctx, output_sp); 3124 bool this_should_stop = true; 3125 3126 switch (this_result) { 3127 case StopHook::StopHookResult::KeepStopped: 3128 // If this hook is set to auto-continue that should override the 3129 // HandleStop result... 3130 if (cur_hook_sp->GetAutoContinue()) 3131 this_should_stop = false; 3132 else 3133 this_should_stop = true; 3134 3135 break; 3136 case StopHook::StopHookResult::RequestContinue: 3137 this_should_stop = false; 3138 break; 3139 case StopHook::StopHookResult::AlreadyContinued: 3140 // We don't have a good way to prohibit people from restarting the 3141 // target willy nilly in a stop hook. If the hook did so, give a 3142 // gentle suggestion here and bag out if the hook processing. 3143 output_sp->Printf("\nAborting stop hooks, hook %" PRIu64 3144 " set the program running.\n" 3145 " Consider using '-G true' to make " 3146 "stop hooks auto-continue.\n", 3147 cur_hook_sp->GetID()); 3148 somebody_restarted = true; 3149 break; 3150 } 3151 // If we're already restarted, stop processing stop hooks. 3152 // FIXME: if we are doing non-stop mode for real, we would have to 3153 // check that OUR thread was restarted, otherwise we should keep 3154 // processing stop hooks. 3155 if (somebody_restarted) 3156 break; 3157 3158 // If anybody wanted to stop, we should all stop. 3159 if (!should_stop) 3160 should_stop = this_should_stop; 3161 } 3162 } 3163 3164 output_sp->Flush(); 3165 3166 // If one of the commands in the stop hook already restarted the target, 3167 // report that fact. 3168 if (somebody_restarted) 3169 return true; 3170 3171 // Finally, if auto-continue was requested, do it now: 3172 // We only compute should_stop against the hook results if a hook got to run 3173 // which is why we have to do this conjoint test. 3174 if ((hooks_ran && !should_stop) || auto_continue) { 3175 Log *log = GetLog(LLDBLog::Process); 3176 Status error = m_process_sp->PrivateResume(); 3177 if (error.Success()) { 3178 LLDB_LOG(log, "Resuming from RunStopHooks"); 3179 return true; 3180 } else { 3181 LLDB_LOG(log, "Resuming from RunStopHooks failed: {0}", error); 3182 return false; 3183 } 3184 } 3185 3186 return false; 3187 } 3188 3189 TargetProperties &Target::GetGlobalProperties() { 3190 // NOTE: intentional leak so we don't crash if global destructor chain gets 3191 // called as other threads still use the result of this function 3192 static TargetProperties *g_settings_ptr = 3193 new TargetProperties(nullptr); 3194 return *g_settings_ptr; 3195 } 3196 3197 Status Target::Install(ProcessLaunchInfo *launch_info) { 3198 Status error; 3199 PlatformSP platform_sp(GetPlatform()); 3200 if (!platform_sp || !platform_sp->IsRemote() || !platform_sp->IsConnected()) 3201 return error; 3202 3203 // Install all files that have an install path when connected to a 3204 // remote platform. If target.auto-install-main-executable is set then 3205 // also install the main executable even if it does not have an explicit 3206 // install path specified. 3207 3208 for (auto module_sp : GetImages().Modules()) { 3209 if (module_sp == GetExecutableModule()) { 3210 MainExecutableInstaller installer{platform_sp, module_sp, 3211 shared_from_this(), *launch_info}; 3212 error = installExecutable(installer); 3213 } else { 3214 ExecutableInstaller installer{platform_sp, module_sp}; 3215 error = installExecutable(installer); 3216 } 3217 3218 if (error.Fail()) 3219 return error; 3220 } 3221 3222 return error; 3223 } 3224 3225 bool Target::ResolveLoadAddress(addr_t load_addr, Address &so_addr, 3226 uint32_t stop_id, bool allow_section_end) { 3227 return m_section_load_history.ResolveLoadAddress(stop_id, load_addr, so_addr, 3228 allow_section_end); 3229 } 3230 3231 bool Target::ResolveFileAddress(lldb::addr_t file_addr, 3232 Address &resolved_addr) { 3233 return m_images.ResolveFileAddress(file_addr, resolved_addr); 3234 } 3235 3236 bool Target::SetSectionLoadAddress(const SectionSP §ion_sp, 3237 addr_t new_section_load_addr, 3238 bool warn_multiple) { 3239 const addr_t old_section_load_addr = 3240 m_section_load_history.GetSectionLoadAddress( 3241 SectionLoadHistory::eStopIDNow, section_sp); 3242 if (old_section_load_addr != new_section_load_addr) { 3243 uint32_t stop_id = 0; 3244 ProcessSP process_sp(GetProcessSP()); 3245 if (process_sp) 3246 stop_id = process_sp->GetStopID(); 3247 else 3248 stop_id = m_section_load_history.GetLastStopID(); 3249 if (m_section_load_history.SetSectionLoadAddress( 3250 stop_id, section_sp, new_section_load_addr, warn_multiple)) 3251 return true; // Return true if the section load address was changed... 3252 } 3253 return false; // Return false to indicate nothing changed 3254 } 3255 3256 size_t Target::UnloadModuleSections(const ModuleList &module_list) { 3257 size_t section_unload_count = 0; 3258 size_t num_modules = module_list.GetSize(); 3259 for (size_t i = 0; i < num_modules; ++i) { 3260 section_unload_count += 3261 UnloadModuleSections(module_list.GetModuleAtIndex(i)); 3262 } 3263 return section_unload_count; 3264 } 3265 3266 size_t Target::UnloadModuleSections(const lldb::ModuleSP &module_sp) { 3267 uint32_t stop_id = 0; 3268 ProcessSP process_sp(GetProcessSP()); 3269 if (process_sp) 3270 stop_id = process_sp->GetStopID(); 3271 else 3272 stop_id = m_section_load_history.GetLastStopID(); 3273 SectionList *sections = module_sp->GetSectionList(); 3274 size_t section_unload_count = 0; 3275 if (sections) { 3276 const uint32_t num_sections = sections->GetNumSections(0); 3277 for (uint32_t i = 0; i < num_sections; ++i) { 3278 section_unload_count += m_section_load_history.SetSectionUnloaded( 3279 stop_id, sections->GetSectionAtIndex(i)); 3280 } 3281 } 3282 return section_unload_count; 3283 } 3284 3285 bool Target::SetSectionUnloaded(const lldb::SectionSP §ion_sp) { 3286 uint32_t stop_id = 0; 3287 ProcessSP process_sp(GetProcessSP()); 3288 if (process_sp) 3289 stop_id = process_sp->GetStopID(); 3290 else 3291 stop_id = m_section_load_history.GetLastStopID(); 3292 return m_section_load_history.SetSectionUnloaded(stop_id, section_sp); 3293 } 3294 3295 bool Target::SetSectionUnloaded(const lldb::SectionSP §ion_sp, 3296 addr_t load_addr) { 3297 uint32_t stop_id = 0; 3298 ProcessSP process_sp(GetProcessSP()); 3299 if (process_sp) 3300 stop_id = process_sp->GetStopID(); 3301 else 3302 stop_id = m_section_load_history.GetLastStopID(); 3303 return m_section_load_history.SetSectionUnloaded(stop_id, section_sp, 3304 load_addr); 3305 } 3306 3307 void Target::ClearAllLoadedSections() { m_section_load_history.Clear(); } 3308 3309 lldb_private::SummaryStatisticsSP Target::GetSummaryStatisticsSPForProviderName( 3310 lldb_private::TypeSummaryImpl &summary_provider) { 3311 return m_summary_statistics_cache.GetSummaryStatisticsForProvider( 3312 summary_provider); 3313 } 3314 3315 SummaryStatisticsCache &Target::GetSummaryStatisticsCache() { 3316 return m_summary_statistics_cache; 3317 } 3318 3319 void Target::SaveScriptedLaunchInfo(lldb_private::ProcessInfo &process_info) { 3320 if (process_info.IsScriptedProcess()) { 3321 // Only copy scripted process launch options. 3322 ProcessLaunchInfo &default_launch_info = const_cast<ProcessLaunchInfo &>( 3323 GetGlobalProperties().GetProcessLaunchInfo()); 3324 default_launch_info.SetProcessPluginName("ScriptedProcess"); 3325 default_launch_info.SetScriptedMetadata(process_info.GetScriptedMetadata()); 3326 SetProcessLaunchInfo(default_launch_info); 3327 } 3328 } 3329 3330 Status Target::Launch(ProcessLaunchInfo &launch_info, Stream *stream) { 3331 m_stats.SetLaunchOrAttachTime(); 3332 Status error; 3333 Log *log = GetLog(LLDBLog::Target); 3334 3335 LLDB_LOGF(log, "Target::%s() called for %s", __FUNCTION__, 3336 launch_info.GetExecutableFile().GetPath().c_str()); 3337 3338 StateType state = eStateInvalid; 3339 3340 // Scope to temporarily get the process state in case someone has manually 3341 // remotely connected already to a process and we can skip the platform 3342 // launching. 3343 { 3344 ProcessSP process_sp(GetProcessSP()); 3345 3346 if (process_sp) { 3347 state = process_sp->GetState(); 3348 LLDB_LOGF(log, 3349 "Target::%s the process exists, and its current state is %s", 3350 __FUNCTION__, StateAsCString(state)); 3351 } else { 3352 LLDB_LOGF(log, "Target::%s the process instance doesn't currently exist.", 3353 __FUNCTION__); 3354 } 3355 } 3356 3357 launch_info.GetFlags().Set(eLaunchFlagDebug); 3358 3359 SaveScriptedLaunchInfo(launch_info); 3360 3361 // Get the value of synchronous execution here. If you wait till after you 3362 // have started to run, then you could have hit a breakpoint, whose command 3363 // might switch the value, and then you'll pick up that incorrect value. 3364 Debugger &debugger = GetDebugger(); 3365 const bool synchronous_execution = 3366 debugger.GetCommandInterpreter().GetSynchronous(); 3367 3368 PlatformSP platform_sp(GetPlatform()); 3369 3370 FinalizeFileActions(launch_info); 3371 3372 if (state == eStateConnected) { 3373 if (launch_info.GetFlags().Test(eLaunchFlagLaunchInTTY)) 3374 return Status::FromErrorString( 3375 "can't launch in tty when launching through a remote connection"); 3376 } 3377 3378 if (!launch_info.GetArchitecture().IsValid()) 3379 launch_info.GetArchitecture() = GetArchitecture(); 3380 3381 // Hijacking events of the process to be created to be sure that all events 3382 // until the first stop are intercepted (in case if platform doesn't define 3383 // its own hijacking listener or if the process is created by the target 3384 // manually, without the platform). 3385 if (!launch_info.GetHijackListener()) 3386 launch_info.SetHijackListener(Listener::MakeListener( 3387 Process::LaunchSynchronousHijackListenerName.data())); 3388 3389 // If we're not already connected to the process, and if we have a platform 3390 // that can launch a process for debugging, go ahead and do that here. 3391 if (state != eStateConnected && platform_sp && 3392 platform_sp->CanDebugProcess() && !launch_info.IsScriptedProcess()) { 3393 LLDB_LOGF(log, "Target::%s asking the platform to debug the process", 3394 __FUNCTION__); 3395 3396 // If there was a previous process, delete it before we make the new one. 3397 // One subtle point, we delete the process before we release the reference 3398 // to m_process_sp. That way even if we are the last owner, the process 3399 // will get Finalized before it gets destroyed. 3400 DeleteCurrentProcess(); 3401 3402 m_process_sp = 3403 GetPlatform()->DebugProcess(launch_info, debugger, *this, error); 3404 3405 } else { 3406 LLDB_LOGF(log, 3407 "Target::%s the platform doesn't know how to debug a " 3408 "process, getting a process plugin to do this for us.", 3409 __FUNCTION__); 3410 3411 if (state == eStateConnected) { 3412 assert(m_process_sp); 3413 } else { 3414 // Use a Process plugin to construct the process. 3415 CreateProcess(launch_info.GetListener(), 3416 launch_info.GetProcessPluginName(), nullptr, false); 3417 } 3418 3419 // Since we didn't have a platform launch the process, launch it here. 3420 if (m_process_sp) { 3421 m_process_sp->HijackProcessEvents(launch_info.GetHijackListener()); 3422 m_process_sp->SetShadowListener(launch_info.GetShadowListener()); 3423 error = m_process_sp->Launch(launch_info); 3424 } 3425 } 3426 3427 if (!error.Success()) 3428 return error; 3429 3430 if (!m_process_sp) 3431 return Status::FromErrorString("failed to launch or debug process"); 3432 3433 bool rebroadcast_first_stop = 3434 !synchronous_execution && 3435 launch_info.GetFlags().Test(eLaunchFlagStopAtEntry); 3436 3437 assert(launch_info.GetHijackListener()); 3438 3439 EventSP first_stop_event_sp; 3440 state = m_process_sp->WaitForProcessToStop(std::nullopt, &first_stop_event_sp, 3441 rebroadcast_first_stop, 3442 launch_info.GetHijackListener()); 3443 m_process_sp->RestoreProcessEvents(); 3444 3445 if (rebroadcast_first_stop) { 3446 assert(first_stop_event_sp); 3447 m_process_sp->BroadcastEvent(first_stop_event_sp); 3448 return error; 3449 } 3450 3451 switch (state) { 3452 case eStateStopped: { 3453 if (launch_info.GetFlags().Test(eLaunchFlagStopAtEntry)) 3454 break; 3455 if (synchronous_execution) 3456 // Now we have handled the stop-from-attach, and we are just 3457 // switching to a synchronous resume. So we should switch to the 3458 // SyncResume hijacker. 3459 m_process_sp->ResumeSynchronous(stream); 3460 else 3461 error = m_process_sp->Resume(); 3462 if (!error.Success()) { 3463 error = Status::FromErrorStringWithFormat( 3464 "process resume at entry point failed: %s", error.AsCString()); 3465 } 3466 } break; 3467 case eStateExited: { 3468 bool with_shell = !!launch_info.GetShell(); 3469 const int exit_status = m_process_sp->GetExitStatus(); 3470 const char *exit_desc = m_process_sp->GetExitDescription(); 3471 std::string desc; 3472 if (exit_desc && exit_desc[0]) 3473 desc = " (" + std::string(exit_desc) + ')'; 3474 if (with_shell) 3475 error = Status::FromErrorStringWithFormat( 3476 "process exited with status %i%s\n" 3477 "'r' and 'run' are aliases that default to launching through a " 3478 "shell.\n" 3479 "Try launching without going through a shell by using " 3480 "'process launch'.", 3481 exit_status, desc.c_str()); 3482 else 3483 error = Status::FromErrorStringWithFormat( 3484 "process exited with status %i%s", exit_status, desc.c_str()); 3485 } break; 3486 default: 3487 error = Status::FromErrorStringWithFormat( 3488 "initial process state wasn't stopped: %s", StateAsCString(state)); 3489 break; 3490 } 3491 return error; 3492 } 3493 3494 void Target::SetTrace(const TraceSP &trace_sp) { m_trace_sp = trace_sp; } 3495 3496 TraceSP Target::GetTrace() { return m_trace_sp; } 3497 3498 llvm::Expected<TraceSP> Target::CreateTrace() { 3499 if (!m_process_sp) 3500 return llvm::createStringError(llvm::inconvertibleErrorCode(), 3501 "A process is required for tracing"); 3502 if (m_trace_sp) 3503 return llvm::createStringError(llvm::inconvertibleErrorCode(), 3504 "A trace already exists for the target"); 3505 3506 llvm::Expected<TraceSupportedResponse> trace_type = 3507 m_process_sp->TraceSupported(); 3508 if (!trace_type) 3509 return llvm::createStringError( 3510 llvm::inconvertibleErrorCode(), "Tracing is not supported. %s", 3511 llvm::toString(trace_type.takeError()).c_str()); 3512 if (llvm::Expected<TraceSP> trace_sp = 3513 Trace::FindPluginForLiveProcess(trace_type->name, *m_process_sp)) 3514 m_trace_sp = *trace_sp; 3515 else 3516 return llvm::createStringError( 3517 llvm::inconvertibleErrorCode(), 3518 "Couldn't create a Trace object for the process. %s", 3519 llvm::toString(trace_sp.takeError()).c_str()); 3520 return m_trace_sp; 3521 } 3522 3523 llvm::Expected<TraceSP> Target::GetTraceOrCreate() { 3524 if (m_trace_sp) 3525 return m_trace_sp; 3526 return CreateTrace(); 3527 } 3528 3529 Status Target::Attach(ProcessAttachInfo &attach_info, Stream *stream) { 3530 m_stats.SetLaunchOrAttachTime(); 3531 auto state = eStateInvalid; 3532 auto process_sp = GetProcessSP(); 3533 if (process_sp) { 3534 state = process_sp->GetState(); 3535 if (process_sp->IsAlive() && state != eStateConnected) { 3536 if (state == eStateAttaching) 3537 return Status::FromErrorString("process attach is in progress"); 3538 return Status::FromErrorString("a process is already being debugged"); 3539 } 3540 } 3541 3542 const ModuleSP old_exec_module_sp = GetExecutableModule(); 3543 3544 // If no process info was specified, then use the target executable name as 3545 // the process to attach to by default 3546 if (!attach_info.ProcessInfoSpecified()) { 3547 if (old_exec_module_sp) 3548 attach_info.GetExecutableFile().SetFilename( 3549 old_exec_module_sp->GetPlatformFileSpec().GetFilename()); 3550 3551 if (!attach_info.ProcessInfoSpecified()) { 3552 return Status::FromErrorString( 3553 "no process specified, create a target with a file, or " 3554 "specify the --pid or --name"); 3555 } 3556 } 3557 3558 const auto platform_sp = 3559 GetDebugger().GetPlatformList().GetSelectedPlatform(); 3560 ListenerSP hijack_listener_sp; 3561 const bool async = attach_info.GetAsync(); 3562 if (!async) { 3563 hijack_listener_sp = Listener::MakeListener( 3564 Process::AttachSynchronousHijackListenerName.data()); 3565 attach_info.SetHijackListener(hijack_listener_sp); 3566 } 3567 3568 Status error; 3569 if (state != eStateConnected && platform_sp != nullptr && 3570 platform_sp->CanDebugProcess() && !attach_info.IsScriptedProcess()) { 3571 SetPlatform(platform_sp); 3572 process_sp = platform_sp->Attach(attach_info, GetDebugger(), this, error); 3573 } else { 3574 if (state != eStateConnected) { 3575 SaveScriptedLaunchInfo(attach_info); 3576 llvm::StringRef plugin_name = attach_info.GetProcessPluginName(); 3577 process_sp = 3578 CreateProcess(attach_info.GetListenerForProcess(GetDebugger()), 3579 plugin_name, nullptr, false); 3580 if (!process_sp) { 3581 error = Status::FromErrorStringWithFormatv( 3582 "failed to create process using plugin '{0}'", 3583 plugin_name.empty() ? "<empty>" : plugin_name); 3584 return error; 3585 } 3586 } 3587 if (hijack_listener_sp) 3588 process_sp->HijackProcessEvents(hijack_listener_sp); 3589 error = process_sp->Attach(attach_info); 3590 } 3591 3592 if (error.Success() && process_sp) { 3593 if (async) { 3594 process_sp->RestoreProcessEvents(); 3595 } else { 3596 // We are stopping all the way out to the user, so update selected frames. 3597 state = process_sp->WaitForProcessToStop( 3598 std::nullopt, nullptr, false, attach_info.GetHijackListener(), stream, 3599 true, SelectMostRelevantFrame); 3600 process_sp->RestoreProcessEvents(); 3601 3602 if (state != eStateStopped) { 3603 const char *exit_desc = process_sp->GetExitDescription(); 3604 if (exit_desc) 3605 error = Status::FromErrorStringWithFormat("%s", exit_desc); 3606 else 3607 error = Status::FromErrorString( 3608 "process did not stop (no such process or permission problem?)"); 3609 process_sp->Destroy(false); 3610 } 3611 } 3612 } 3613 return error; 3614 } 3615 3616 void Target::FinalizeFileActions(ProcessLaunchInfo &info) { 3617 Log *log = GetLog(LLDBLog::Process); 3618 3619 // Finalize the file actions, and if none were given, default to opening up a 3620 // pseudo terminal 3621 PlatformSP platform_sp = GetPlatform(); 3622 const bool default_to_use_pty = 3623 m_platform_sp ? m_platform_sp->IsHost() : false; 3624 LLDB_LOG( 3625 log, 3626 "have platform={0}, platform_sp->IsHost()={1}, default_to_use_pty={2}", 3627 bool(platform_sp), 3628 platform_sp ? (platform_sp->IsHost() ? "true" : "false") : "n/a", 3629 default_to_use_pty); 3630 3631 // If nothing for stdin or stdout or stderr was specified, then check the 3632 // process for any default settings that were set with "settings set" 3633 if (info.GetFileActionForFD(STDIN_FILENO) == nullptr || 3634 info.GetFileActionForFD(STDOUT_FILENO) == nullptr || 3635 info.GetFileActionForFD(STDERR_FILENO) == nullptr) { 3636 LLDB_LOG(log, "at least one of stdin/stdout/stderr was not set, evaluating " 3637 "default handling"); 3638 3639 if (info.GetFlags().Test(eLaunchFlagLaunchInTTY)) { 3640 // Do nothing, if we are launching in a remote terminal no file actions 3641 // should be done at all. 3642 return; 3643 } 3644 3645 if (info.GetFlags().Test(eLaunchFlagDisableSTDIO)) { 3646 LLDB_LOG(log, "eLaunchFlagDisableSTDIO set, adding suppression action " 3647 "for stdin, stdout and stderr"); 3648 info.AppendSuppressFileAction(STDIN_FILENO, true, false); 3649 info.AppendSuppressFileAction(STDOUT_FILENO, false, true); 3650 info.AppendSuppressFileAction(STDERR_FILENO, false, true); 3651 } else { 3652 // Check for any values that might have gotten set with any of: (lldb) 3653 // settings set target.input-path (lldb) settings set target.output-path 3654 // (lldb) settings set target.error-path 3655 FileSpec in_file_spec; 3656 FileSpec out_file_spec; 3657 FileSpec err_file_spec; 3658 // Only override with the target settings if we don't already have an 3659 // action for in, out or error 3660 if (info.GetFileActionForFD(STDIN_FILENO) == nullptr) 3661 in_file_spec = GetStandardInputPath(); 3662 if (info.GetFileActionForFD(STDOUT_FILENO) == nullptr) 3663 out_file_spec = GetStandardOutputPath(); 3664 if (info.GetFileActionForFD(STDERR_FILENO) == nullptr) 3665 err_file_spec = GetStandardErrorPath(); 3666 3667 LLDB_LOG(log, "target stdin='{0}', target stdout='{1}', stderr='{2}'", 3668 in_file_spec, out_file_spec, err_file_spec); 3669 3670 if (in_file_spec) { 3671 info.AppendOpenFileAction(STDIN_FILENO, in_file_spec, true, false); 3672 LLDB_LOG(log, "appended stdin open file action for {0}", in_file_spec); 3673 } 3674 3675 if (out_file_spec) { 3676 info.AppendOpenFileAction(STDOUT_FILENO, out_file_spec, false, true); 3677 LLDB_LOG(log, "appended stdout open file action for {0}", 3678 out_file_spec); 3679 } 3680 3681 if (err_file_spec) { 3682 info.AppendOpenFileAction(STDERR_FILENO, err_file_spec, false, true); 3683 LLDB_LOG(log, "appended stderr open file action for {0}", 3684 err_file_spec); 3685 } 3686 3687 if (default_to_use_pty) { 3688 llvm::Error Err = info.SetUpPtyRedirection(); 3689 LLDB_LOG_ERROR(log, std::move(Err), "SetUpPtyRedirection failed: {0}"); 3690 } 3691 } 3692 } 3693 } 3694 3695 void Target::AddDummySignal(llvm::StringRef name, LazyBool pass, LazyBool notify, 3696 LazyBool stop) { 3697 if (name.empty()) 3698 return; 3699 // Don't add a signal if all the actions are trivial: 3700 if (pass == eLazyBoolCalculate && notify == eLazyBoolCalculate 3701 && stop == eLazyBoolCalculate) 3702 return; 3703 3704 auto& elem = m_dummy_signals[name]; 3705 elem.pass = pass; 3706 elem.notify = notify; 3707 elem.stop = stop; 3708 } 3709 3710 bool Target::UpdateSignalFromDummy(UnixSignalsSP signals_sp, 3711 const DummySignalElement &elem) { 3712 if (!signals_sp) 3713 return false; 3714 3715 int32_t signo 3716 = signals_sp->GetSignalNumberFromName(elem.first().str().c_str()); 3717 if (signo == LLDB_INVALID_SIGNAL_NUMBER) 3718 return false; 3719 3720 if (elem.second.pass == eLazyBoolYes) 3721 signals_sp->SetShouldSuppress(signo, false); 3722 else if (elem.second.pass == eLazyBoolNo) 3723 signals_sp->SetShouldSuppress(signo, true); 3724 3725 if (elem.second.notify == eLazyBoolYes) 3726 signals_sp->SetShouldNotify(signo, true); 3727 else if (elem.second.notify == eLazyBoolNo) 3728 signals_sp->SetShouldNotify(signo, false); 3729 3730 if (elem.second.stop == eLazyBoolYes) 3731 signals_sp->SetShouldStop(signo, true); 3732 else if (elem.second.stop == eLazyBoolNo) 3733 signals_sp->SetShouldStop(signo, false); 3734 return true; 3735 } 3736 3737 bool Target::ResetSignalFromDummy(UnixSignalsSP signals_sp, 3738 const DummySignalElement &elem) { 3739 if (!signals_sp) 3740 return false; 3741 int32_t signo 3742 = signals_sp->GetSignalNumberFromName(elem.first().str().c_str()); 3743 if (signo == LLDB_INVALID_SIGNAL_NUMBER) 3744 return false; 3745 bool do_pass = elem.second.pass != eLazyBoolCalculate; 3746 bool do_stop = elem.second.stop != eLazyBoolCalculate; 3747 bool do_notify = elem.second.notify != eLazyBoolCalculate; 3748 signals_sp->ResetSignal(signo, do_stop, do_notify, do_pass); 3749 return true; 3750 } 3751 3752 void Target::UpdateSignalsFromDummy(UnixSignalsSP signals_sp, 3753 StreamSP warning_stream_sp) { 3754 if (!signals_sp) 3755 return; 3756 3757 for (const auto &elem : m_dummy_signals) { 3758 if (!UpdateSignalFromDummy(signals_sp, elem)) 3759 warning_stream_sp->Printf("Target signal '%s' not found in process\n", 3760 elem.first().str().c_str()); 3761 } 3762 } 3763 3764 void Target::ClearDummySignals(Args &signal_names) { 3765 ProcessSP process_sp = GetProcessSP(); 3766 // The simplest case, delete them all with no process to update. 3767 if (signal_names.GetArgumentCount() == 0 && !process_sp) { 3768 m_dummy_signals.clear(); 3769 return; 3770 } 3771 UnixSignalsSP signals_sp; 3772 if (process_sp) 3773 signals_sp = process_sp->GetUnixSignals(); 3774 3775 for (const Args::ArgEntry &entry : signal_names) { 3776 const char *signal_name = entry.c_str(); 3777 auto elem = m_dummy_signals.find(signal_name); 3778 // If we didn't find it go on. 3779 // FIXME: Should I pipe error handling through here? 3780 if (elem == m_dummy_signals.end()) { 3781 continue; 3782 } 3783 if (signals_sp) 3784 ResetSignalFromDummy(signals_sp, *elem); 3785 m_dummy_signals.erase(elem); 3786 } 3787 } 3788 3789 void Target::PrintDummySignals(Stream &strm, Args &signal_args) { 3790 strm.Printf("NAME PASS STOP NOTIFY\n"); 3791 strm.Printf("=========== ======= ======= =======\n"); 3792 3793 auto str_for_lazy = [] (LazyBool lazy) -> const char * { 3794 switch (lazy) { 3795 case eLazyBoolCalculate: return "not set"; 3796 case eLazyBoolYes: return "true "; 3797 case eLazyBoolNo: return "false "; 3798 } 3799 llvm_unreachable("Fully covered switch above!"); 3800 }; 3801 size_t num_args = signal_args.GetArgumentCount(); 3802 for (const auto &elem : m_dummy_signals) { 3803 bool print_it = false; 3804 for (size_t idx = 0; idx < num_args; idx++) { 3805 if (elem.first() == signal_args.GetArgumentAtIndex(idx)) { 3806 print_it = true; 3807 break; 3808 } 3809 } 3810 if (print_it) { 3811 strm.Printf("%-11s ", elem.first().str().c_str()); 3812 strm.Printf("%s %s %s\n", str_for_lazy(elem.second.pass), 3813 str_for_lazy(elem.second.stop), 3814 str_for_lazy(elem.second.notify)); 3815 } 3816 } 3817 } 3818 3819 // Target::StopHook 3820 Target::StopHook::StopHook(lldb::TargetSP target_sp, lldb::user_id_t uid) 3821 : UserID(uid), m_target_sp(target_sp), m_specifier_sp(), 3822 m_thread_spec_up() {} 3823 3824 Target::StopHook::StopHook(const StopHook &rhs) 3825 : UserID(rhs.GetID()), m_target_sp(rhs.m_target_sp), 3826 m_specifier_sp(rhs.m_specifier_sp), m_thread_spec_up(), 3827 m_active(rhs.m_active), m_auto_continue(rhs.m_auto_continue) { 3828 if (rhs.m_thread_spec_up) 3829 m_thread_spec_up = std::make_unique<ThreadSpec>(*rhs.m_thread_spec_up); 3830 } 3831 3832 void Target::StopHook::SetSpecifier(SymbolContextSpecifier *specifier) { 3833 m_specifier_sp.reset(specifier); 3834 } 3835 3836 void Target::StopHook::SetThreadSpecifier(ThreadSpec *specifier) { 3837 m_thread_spec_up.reset(specifier); 3838 } 3839 3840 bool Target::StopHook::ExecutionContextPasses(const ExecutionContext &exc_ctx) { 3841 SymbolContextSpecifier *specifier = GetSpecifier(); 3842 if (!specifier) 3843 return true; 3844 3845 bool will_run = true; 3846 if (exc_ctx.GetFramePtr()) 3847 will_run = GetSpecifier()->SymbolContextMatches( 3848 exc_ctx.GetFramePtr()->GetSymbolContext(eSymbolContextEverything)); 3849 if (will_run && GetThreadSpecifier() != nullptr) 3850 will_run = 3851 GetThreadSpecifier()->ThreadPassesBasicTests(exc_ctx.GetThreadRef()); 3852 3853 return will_run; 3854 } 3855 3856 void Target::StopHook::GetDescription(Stream &s, 3857 lldb::DescriptionLevel level) const { 3858 3859 // For brief descriptions, only print the subclass description: 3860 if (level == eDescriptionLevelBrief) { 3861 GetSubclassDescription(s, level); 3862 return; 3863 } 3864 3865 unsigned indent_level = s.GetIndentLevel(); 3866 3867 s.SetIndentLevel(indent_level + 2); 3868 3869 s.Printf("Hook: %" PRIu64 "\n", GetID()); 3870 if (m_active) 3871 s.Indent("State: enabled\n"); 3872 else 3873 s.Indent("State: disabled\n"); 3874 3875 if (m_auto_continue) 3876 s.Indent("AutoContinue on\n"); 3877 3878 if (m_specifier_sp) { 3879 s.Indent(); 3880 s.PutCString("Specifier:\n"); 3881 s.SetIndentLevel(indent_level + 4); 3882 m_specifier_sp->GetDescription(&s, level); 3883 s.SetIndentLevel(indent_level + 2); 3884 } 3885 3886 if (m_thread_spec_up) { 3887 StreamString tmp; 3888 s.Indent("Thread:\n"); 3889 m_thread_spec_up->GetDescription(&tmp, level); 3890 s.SetIndentLevel(indent_level + 4); 3891 s.Indent(tmp.GetString()); 3892 s.PutCString("\n"); 3893 s.SetIndentLevel(indent_level + 2); 3894 } 3895 GetSubclassDescription(s, level); 3896 } 3897 3898 void Target::StopHookCommandLine::GetSubclassDescription( 3899 Stream &s, lldb::DescriptionLevel level) const { 3900 // The brief description just prints the first command. 3901 if (level == eDescriptionLevelBrief) { 3902 if (m_commands.GetSize() == 1) 3903 s.PutCString(m_commands.GetStringAtIndex(0)); 3904 return; 3905 } 3906 s.Indent("Commands: \n"); 3907 s.SetIndentLevel(s.GetIndentLevel() + 4); 3908 uint32_t num_commands = m_commands.GetSize(); 3909 for (uint32_t i = 0; i < num_commands; i++) { 3910 s.Indent(m_commands.GetStringAtIndex(i)); 3911 s.PutCString("\n"); 3912 } 3913 s.SetIndentLevel(s.GetIndentLevel() - 4); 3914 } 3915 3916 // Target::StopHookCommandLine 3917 void Target::StopHookCommandLine::SetActionFromString(const std::string &string) { 3918 GetCommands().SplitIntoLines(string); 3919 } 3920 3921 void Target::StopHookCommandLine::SetActionFromStrings( 3922 const std::vector<std::string> &strings) { 3923 for (auto string : strings) 3924 GetCommands().AppendString(string.c_str()); 3925 } 3926 3927 Target::StopHook::StopHookResult 3928 Target::StopHookCommandLine::HandleStop(ExecutionContext &exc_ctx, 3929 StreamSP output_sp) { 3930 assert(exc_ctx.GetTargetPtr() && "Can't call PerformAction on a context " 3931 "with no target"); 3932 3933 if (!m_commands.GetSize()) 3934 return StopHookResult::KeepStopped; 3935 3936 CommandReturnObject result(false); 3937 result.SetImmediateOutputStream(output_sp); 3938 result.SetInteractive(false); 3939 Debugger &debugger = exc_ctx.GetTargetPtr()->GetDebugger(); 3940 CommandInterpreterRunOptions options; 3941 options.SetStopOnContinue(true); 3942 options.SetStopOnError(true); 3943 options.SetEchoCommands(false); 3944 options.SetPrintResults(true); 3945 options.SetPrintErrors(true); 3946 options.SetAddToHistory(false); 3947 3948 // Force Async: 3949 bool old_async = debugger.GetAsyncExecution(); 3950 debugger.SetAsyncExecution(true); 3951 debugger.GetCommandInterpreter().HandleCommands(GetCommands(), exc_ctx, 3952 options, result); 3953 debugger.SetAsyncExecution(old_async); 3954 lldb::ReturnStatus status = result.GetStatus(); 3955 if (status == eReturnStatusSuccessContinuingNoResult || 3956 status == eReturnStatusSuccessContinuingResult) 3957 return StopHookResult::AlreadyContinued; 3958 return StopHookResult::KeepStopped; 3959 } 3960 3961 // Target::StopHookScripted 3962 Status Target::StopHookScripted::SetScriptCallback( 3963 std::string class_name, StructuredData::ObjectSP extra_args_sp) { 3964 Status error; 3965 3966 ScriptInterpreter *script_interp = 3967 GetTarget()->GetDebugger().GetScriptInterpreter(); 3968 if (!script_interp) { 3969 error = Status::FromErrorString("No script interpreter installed."); 3970 return error; 3971 } 3972 3973 m_interface_sp = script_interp->CreateScriptedStopHookInterface(); 3974 if (!m_interface_sp) { 3975 error = Status::FromErrorStringWithFormat( 3976 "ScriptedStopHook::%s () - ERROR: %s", __FUNCTION__, 3977 "Script interpreter couldn't create Scripted Stop Hook Interface"); 3978 return error; 3979 } 3980 3981 m_class_name = class_name; 3982 m_extra_args.SetObjectSP(extra_args_sp); 3983 3984 auto obj_or_err = m_interface_sp->CreatePluginObject( 3985 m_class_name, GetTarget(), m_extra_args); 3986 if (!obj_or_err) { 3987 return Status::FromError(obj_or_err.takeError()); 3988 } 3989 3990 StructuredData::ObjectSP object_sp = *obj_or_err; 3991 if (!object_sp || !object_sp->IsValid()) { 3992 error = Status::FromErrorStringWithFormat( 3993 "ScriptedStopHook::%s () - ERROR: %s", __FUNCTION__, 3994 "Failed to create valid script object"); 3995 return error; 3996 } 3997 3998 return {}; 3999 } 4000 4001 Target::StopHook::StopHookResult 4002 Target::StopHookScripted::HandleStop(ExecutionContext &exc_ctx, 4003 StreamSP output_sp) { 4004 assert(exc_ctx.GetTargetPtr() && "Can't call HandleStop on a context " 4005 "with no target"); 4006 4007 if (!m_interface_sp) 4008 return StopHookResult::KeepStopped; 4009 4010 lldb::StreamSP stream = std::make_shared<lldb_private::StreamString>(); 4011 auto should_stop_or_err = m_interface_sp->HandleStop(exc_ctx, stream); 4012 output_sp->PutCString( 4013 reinterpret_cast<StreamString *>(stream.get())->GetData()); 4014 if (!should_stop_or_err) 4015 return StopHookResult::KeepStopped; 4016 4017 return *should_stop_or_err ? StopHookResult::KeepStopped 4018 : StopHookResult::RequestContinue; 4019 } 4020 4021 void Target::StopHookScripted::GetSubclassDescription( 4022 Stream &s, lldb::DescriptionLevel level) const { 4023 if (level == eDescriptionLevelBrief) { 4024 s.PutCString(m_class_name); 4025 return; 4026 } 4027 s.Indent("Class:"); 4028 s.Printf("%s\n", m_class_name.c_str()); 4029 4030 // Now print the extra args: 4031 // FIXME: We should use StructuredData.GetDescription on the m_extra_args 4032 // but that seems to rely on some printing plugin that doesn't exist. 4033 if (!m_extra_args.IsValid()) 4034 return; 4035 StructuredData::ObjectSP object_sp = m_extra_args.GetObjectSP(); 4036 if (!object_sp || !object_sp->IsValid()) 4037 return; 4038 4039 StructuredData::Dictionary *as_dict = object_sp->GetAsDictionary(); 4040 if (!as_dict || !as_dict->IsValid()) 4041 return; 4042 4043 uint32_t num_keys = as_dict->GetSize(); 4044 if (num_keys == 0) 4045 return; 4046 4047 s.Indent("Args:\n"); 4048 s.SetIndentLevel(s.GetIndentLevel() + 4); 4049 4050 auto print_one_element = [&s](llvm::StringRef key, 4051 StructuredData::Object *object) { 4052 s.Indent(); 4053 s.Format("{0} : {1}\n", key, object->GetStringValue()); 4054 return true; 4055 }; 4056 4057 as_dict->ForEach(print_one_element); 4058 4059 s.SetIndentLevel(s.GetIndentLevel() - 4); 4060 } 4061 4062 static constexpr OptionEnumValueElement g_dynamic_value_types[] = { 4063 { 4064 eNoDynamicValues, 4065 "no-dynamic-values", 4066 "Don't calculate the dynamic type of values", 4067 }, 4068 { 4069 eDynamicCanRunTarget, 4070 "run-target", 4071 "Calculate the dynamic type of values " 4072 "even if you have to run the target.", 4073 }, 4074 { 4075 eDynamicDontRunTarget, 4076 "no-run-target", 4077 "Calculate the dynamic type of values, but don't run the target.", 4078 }, 4079 }; 4080 4081 OptionEnumValues lldb_private::GetDynamicValueTypes() { 4082 return OptionEnumValues(g_dynamic_value_types); 4083 } 4084 4085 static constexpr OptionEnumValueElement g_inline_breakpoint_enums[] = { 4086 { 4087 eInlineBreakpointsNever, 4088 "never", 4089 "Never look for inline breakpoint locations (fastest). This setting " 4090 "should only be used if you know that no inlining occurs in your" 4091 "programs.", 4092 }, 4093 { 4094 eInlineBreakpointsHeaders, 4095 "headers", 4096 "Only check for inline breakpoint locations when setting breakpoints " 4097 "in header files, but not when setting breakpoint in implementation " 4098 "source files (default).", 4099 }, 4100 { 4101 eInlineBreakpointsAlways, 4102 "always", 4103 "Always look for inline breakpoint locations when setting file and " 4104 "line breakpoints (slower but most accurate).", 4105 }, 4106 }; 4107 4108 enum x86DisassemblyFlavor { 4109 eX86DisFlavorDefault, 4110 eX86DisFlavorIntel, 4111 eX86DisFlavorATT 4112 }; 4113 4114 static constexpr OptionEnumValueElement g_x86_dis_flavor_value_types[] = { 4115 { 4116 eX86DisFlavorDefault, 4117 "default", 4118 "Disassembler default (currently att).", 4119 }, 4120 { 4121 eX86DisFlavorIntel, 4122 "intel", 4123 "Intel disassembler flavor.", 4124 }, 4125 { 4126 eX86DisFlavorATT, 4127 "att", 4128 "AT&T disassembler flavor.", 4129 }, 4130 }; 4131 4132 static constexpr OptionEnumValueElement g_import_std_module_value_types[] = { 4133 { 4134 eImportStdModuleFalse, 4135 "false", 4136 "Never import the 'std' C++ module in the expression parser.", 4137 }, 4138 { 4139 eImportStdModuleFallback, 4140 "fallback", 4141 "Retry evaluating expressions with an imported 'std' C++ module if they" 4142 " failed to parse without the module. This allows evaluating more " 4143 "complex expressions involving C++ standard library types." 4144 }, 4145 { 4146 eImportStdModuleTrue, 4147 "true", 4148 "Always import the 'std' C++ module. This allows evaluating more " 4149 "complex expressions involving C++ standard library types. This feature" 4150 " is experimental." 4151 }, 4152 }; 4153 4154 static constexpr OptionEnumValueElement 4155 g_dynamic_class_info_helper_value_types[] = { 4156 { 4157 eDynamicClassInfoHelperAuto, 4158 "auto", 4159 "Automatically determine the most appropriate method for the " 4160 "target OS.", 4161 }, 4162 {eDynamicClassInfoHelperRealizedClassesStruct, "RealizedClassesStruct", 4163 "Prefer using the realized classes struct."}, 4164 {eDynamicClassInfoHelperCopyRealizedClassList, "CopyRealizedClassList", 4165 "Prefer using the CopyRealizedClassList API."}, 4166 {eDynamicClassInfoHelperGetRealizedClassList, "GetRealizedClassList", 4167 "Prefer using the GetRealizedClassList API."}, 4168 }; 4169 4170 static constexpr OptionEnumValueElement g_hex_immediate_style_values[] = { 4171 { 4172 Disassembler::eHexStyleC, 4173 "c", 4174 "C-style (0xffff).", 4175 }, 4176 { 4177 Disassembler::eHexStyleAsm, 4178 "asm", 4179 "Asm-style (0ffffh).", 4180 }, 4181 }; 4182 4183 static constexpr OptionEnumValueElement g_load_script_from_sym_file_values[] = { 4184 { 4185 eLoadScriptFromSymFileTrue, 4186 "true", 4187 "Load debug scripts inside symbol files", 4188 }, 4189 { 4190 eLoadScriptFromSymFileFalse, 4191 "false", 4192 "Do not load debug scripts inside symbol files.", 4193 }, 4194 { 4195 eLoadScriptFromSymFileWarn, 4196 "warn", 4197 "Warn about debug scripts inside symbol files but do not load them.", 4198 }, 4199 }; 4200 4201 static constexpr OptionEnumValueElement g_load_cwd_lldbinit_values[] = { 4202 { 4203 eLoadCWDlldbinitTrue, 4204 "true", 4205 "Load .lldbinit files from current directory", 4206 }, 4207 { 4208 eLoadCWDlldbinitFalse, 4209 "false", 4210 "Do not load .lldbinit files from current directory", 4211 }, 4212 { 4213 eLoadCWDlldbinitWarn, 4214 "warn", 4215 "Warn about loading .lldbinit files from current directory", 4216 }, 4217 }; 4218 4219 static constexpr OptionEnumValueElement g_memory_module_load_level_values[] = { 4220 { 4221 eMemoryModuleLoadLevelMinimal, 4222 "minimal", 4223 "Load minimal information when loading modules from memory. Currently " 4224 "this setting loads sections only.", 4225 }, 4226 { 4227 eMemoryModuleLoadLevelPartial, 4228 "partial", 4229 "Load partial information when loading modules from memory. Currently " 4230 "this setting loads sections and function bounds.", 4231 }, 4232 { 4233 eMemoryModuleLoadLevelComplete, 4234 "complete", 4235 "Load complete information when loading modules from memory. Currently " 4236 "this setting loads sections and all symbols.", 4237 }, 4238 }; 4239 4240 #define LLDB_PROPERTIES_target 4241 #include "TargetProperties.inc" 4242 4243 enum { 4244 #define LLDB_PROPERTIES_target 4245 #include "TargetPropertiesEnum.inc" 4246 ePropertyExperimental, 4247 }; 4248 4249 class TargetOptionValueProperties 4250 : public Cloneable<TargetOptionValueProperties, OptionValueProperties> { 4251 public: 4252 TargetOptionValueProperties(llvm::StringRef name) : Cloneable(name) {} 4253 4254 const Property * 4255 GetPropertyAtIndex(size_t idx, 4256 const ExecutionContext *exe_ctx = nullptr) const override { 4257 // When getting the value for a key from the target options, we will always 4258 // try and grab the setting from the current target if there is one. Else 4259 // we just use the one from this instance. 4260 if (exe_ctx) { 4261 Target *target = exe_ctx->GetTargetPtr(); 4262 if (target) { 4263 TargetOptionValueProperties *target_properties = 4264 static_cast<TargetOptionValueProperties *>( 4265 target->GetValueProperties().get()); 4266 if (this != target_properties) 4267 return target_properties->ProtectedGetPropertyAtIndex(idx); 4268 } 4269 } 4270 return ProtectedGetPropertyAtIndex(idx); 4271 } 4272 }; 4273 4274 // TargetProperties 4275 #define LLDB_PROPERTIES_target_experimental 4276 #include "TargetProperties.inc" 4277 4278 enum { 4279 #define LLDB_PROPERTIES_target_experimental 4280 #include "TargetPropertiesEnum.inc" 4281 }; 4282 4283 class TargetExperimentalOptionValueProperties 4284 : public Cloneable<TargetExperimentalOptionValueProperties, 4285 OptionValueProperties> { 4286 public: 4287 TargetExperimentalOptionValueProperties() 4288 : Cloneable(Properties::GetExperimentalSettingsName()) {} 4289 }; 4290 4291 TargetExperimentalProperties::TargetExperimentalProperties() 4292 : Properties(OptionValuePropertiesSP( 4293 new TargetExperimentalOptionValueProperties())) { 4294 m_collection_sp->Initialize(g_target_experimental_properties); 4295 } 4296 4297 // TargetProperties 4298 TargetProperties::TargetProperties(Target *target) 4299 : Properties(), m_launch_info(), m_target(target) { 4300 if (target) { 4301 m_collection_sp = 4302 OptionValueProperties::CreateLocalCopy(Target::GetGlobalProperties()); 4303 4304 // Set callbacks to update launch_info whenever "settins set" updated any 4305 // of these properties 4306 m_collection_sp->SetValueChangedCallback( 4307 ePropertyArg0, [this] { Arg0ValueChangedCallback(); }); 4308 m_collection_sp->SetValueChangedCallback( 4309 ePropertyRunArgs, [this] { RunArgsValueChangedCallback(); }); 4310 m_collection_sp->SetValueChangedCallback( 4311 ePropertyEnvVars, [this] { EnvVarsValueChangedCallback(); }); 4312 m_collection_sp->SetValueChangedCallback( 4313 ePropertyUnsetEnvVars, [this] { EnvVarsValueChangedCallback(); }); 4314 m_collection_sp->SetValueChangedCallback( 4315 ePropertyInheritEnv, [this] { EnvVarsValueChangedCallback(); }); 4316 m_collection_sp->SetValueChangedCallback( 4317 ePropertyInputPath, [this] { InputPathValueChangedCallback(); }); 4318 m_collection_sp->SetValueChangedCallback( 4319 ePropertyOutputPath, [this] { OutputPathValueChangedCallback(); }); 4320 m_collection_sp->SetValueChangedCallback( 4321 ePropertyErrorPath, [this] { ErrorPathValueChangedCallback(); }); 4322 m_collection_sp->SetValueChangedCallback(ePropertyDetachOnError, [this] { 4323 DetachOnErrorValueChangedCallback(); 4324 }); 4325 m_collection_sp->SetValueChangedCallback( 4326 ePropertyDisableASLR, [this] { DisableASLRValueChangedCallback(); }); 4327 m_collection_sp->SetValueChangedCallback( 4328 ePropertyInheritTCC, [this] { InheritTCCValueChangedCallback(); }); 4329 m_collection_sp->SetValueChangedCallback( 4330 ePropertyDisableSTDIO, [this] { DisableSTDIOValueChangedCallback(); }); 4331 4332 m_collection_sp->SetValueChangedCallback( 4333 ePropertySaveObjectsDir, [this] { CheckJITObjectsDir(); }); 4334 m_experimental_properties_up = 4335 std::make_unique<TargetExperimentalProperties>(); 4336 m_collection_sp->AppendProperty( 4337 Properties::GetExperimentalSettingsName(), 4338 "Experimental settings - setting these won't produce " 4339 "errors if the setting is not present.", 4340 true, m_experimental_properties_up->GetValueProperties()); 4341 } else { 4342 m_collection_sp = std::make_shared<TargetOptionValueProperties>("target"); 4343 m_collection_sp->Initialize(g_target_properties); 4344 m_experimental_properties_up = 4345 std::make_unique<TargetExperimentalProperties>(); 4346 m_collection_sp->AppendProperty( 4347 Properties::GetExperimentalSettingsName(), 4348 "Experimental settings - setting these won't produce " 4349 "errors if the setting is not present.", 4350 true, m_experimental_properties_up->GetValueProperties()); 4351 m_collection_sp->AppendProperty( 4352 "process", "Settings specific to processes.", true, 4353 Process::GetGlobalProperties().GetValueProperties()); 4354 m_collection_sp->SetValueChangedCallback( 4355 ePropertySaveObjectsDir, [this] { CheckJITObjectsDir(); }); 4356 } 4357 } 4358 4359 TargetProperties::~TargetProperties() = default; 4360 4361 void TargetProperties::UpdateLaunchInfoFromProperties() { 4362 Arg0ValueChangedCallback(); 4363 RunArgsValueChangedCallback(); 4364 EnvVarsValueChangedCallback(); 4365 InputPathValueChangedCallback(); 4366 OutputPathValueChangedCallback(); 4367 ErrorPathValueChangedCallback(); 4368 DetachOnErrorValueChangedCallback(); 4369 DisableASLRValueChangedCallback(); 4370 InheritTCCValueChangedCallback(); 4371 DisableSTDIOValueChangedCallback(); 4372 } 4373 4374 std::optional<bool> TargetProperties::GetExperimentalPropertyValue( 4375 size_t prop_idx, ExecutionContext *exe_ctx) const { 4376 const Property *exp_property = 4377 m_collection_sp->GetPropertyAtIndex(ePropertyExperimental, exe_ctx); 4378 OptionValueProperties *exp_values = 4379 exp_property->GetValue()->GetAsProperties(); 4380 if (exp_values) 4381 return exp_values->GetPropertyAtIndexAs<bool>(prop_idx, exe_ctx); 4382 return std::nullopt; 4383 } 4384 4385 bool TargetProperties::GetInjectLocalVariables( 4386 ExecutionContext *exe_ctx) const { 4387 return GetExperimentalPropertyValue(ePropertyInjectLocalVars, exe_ctx) 4388 .value_or(true); 4389 } 4390 4391 bool TargetProperties::GetUseDIL(ExecutionContext *exe_ctx) const { 4392 const Property *exp_property = 4393 m_collection_sp->GetPropertyAtIndex(ePropertyExperimental, exe_ctx); 4394 OptionValueProperties *exp_values = 4395 exp_property->GetValue()->GetAsProperties(); 4396 if (exp_values) 4397 return exp_values->GetPropertyAtIndexAs<bool>(ePropertyUseDIL, exe_ctx) 4398 .value_or(false); 4399 else 4400 return true; 4401 } 4402 4403 void TargetProperties::SetUseDIL(ExecutionContext *exe_ctx, bool b) { 4404 const Property *exp_property = 4405 m_collection_sp->GetPropertyAtIndex(ePropertyExperimental, exe_ctx); 4406 OptionValueProperties *exp_values = 4407 exp_property->GetValue()->GetAsProperties(); 4408 if (exp_values) 4409 exp_values->SetPropertyAtIndex(ePropertyUseDIL, true, exe_ctx); 4410 } 4411 4412 ArchSpec TargetProperties::GetDefaultArchitecture() const { 4413 const uint32_t idx = ePropertyDefaultArch; 4414 return GetPropertyAtIndexAs<ArchSpec>(idx, {}); 4415 } 4416 4417 void TargetProperties::SetDefaultArchitecture(const ArchSpec &arch) { 4418 const uint32_t idx = ePropertyDefaultArch; 4419 SetPropertyAtIndex(idx, arch); 4420 } 4421 4422 bool TargetProperties::GetMoveToNearestCode() const { 4423 const uint32_t idx = ePropertyMoveToNearestCode; 4424 return GetPropertyAtIndexAs<bool>( 4425 idx, g_target_properties[idx].default_uint_value != 0); 4426 } 4427 4428 lldb::DynamicValueType TargetProperties::GetPreferDynamicValue() const { 4429 const uint32_t idx = ePropertyPreferDynamic; 4430 return GetPropertyAtIndexAs<lldb::DynamicValueType>( 4431 idx, static_cast<lldb::DynamicValueType>( 4432 g_target_properties[idx].default_uint_value)); 4433 } 4434 4435 bool TargetProperties::SetPreferDynamicValue(lldb::DynamicValueType d) { 4436 const uint32_t idx = ePropertyPreferDynamic; 4437 return SetPropertyAtIndex(idx, d); 4438 } 4439 4440 bool TargetProperties::GetPreloadSymbols() const { 4441 if (INTERRUPT_REQUESTED(m_target->GetDebugger(), 4442 "Interrupted checking preload symbols")) { 4443 return false; 4444 } 4445 const uint32_t idx = ePropertyPreloadSymbols; 4446 return GetPropertyAtIndexAs<bool>( 4447 idx, g_target_properties[idx].default_uint_value != 0); 4448 } 4449 4450 void TargetProperties::SetPreloadSymbols(bool b) { 4451 const uint32_t idx = ePropertyPreloadSymbols; 4452 SetPropertyAtIndex(idx, b); 4453 } 4454 4455 bool TargetProperties::GetDisableASLR() const { 4456 const uint32_t idx = ePropertyDisableASLR; 4457 return GetPropertyAtIndexAs<bool>( 4458 idx, g_target_properties[idx].default_uint_value != 0); 4459 } 4460 4461 void TargetProperties::SetDisableASLR(bool b) { 4462 const uint32_t idx = ePropertyDisableASLR; 4463 SetPropertyAtIndex(idx, b); 4464 } 4465 4466 bool TargetProperties::GetInheritTCC() const { 4467 const uint32_t idx = ePropertyInheritTCC; 4468 return GetPropertyAtIndexAs<bool>( 4469 idx, g_target_properties[idx].default_uint_value != 0); 4470 } 4471 4472 void TargetProperties::SetInheritTCC(bool b) { 4473 const uint32_t idx = ePropertyInheritTCC; 4474 SetPropertyAtIndex(idx, b); 4475 } 4476 4477 bool TargetProperties::GetDetachOnError() const { 4478 const uint32_t idx = ePropertyDetachOnError; 4479 return GetPropertyAtIndexAs<bool>( 4480 idx, g_target_properties[idx].default_uint_value != 0); 4481 } 4482 4483 void TargetProperties::SetDetachOnError(bool b) { 4484 const uint32_t idx = ePropertyDetachOnError; 4485 SetPropertyAtIndex(idx, b); 4486 } 4487 4488 bool TargetProperties::GetDisableSTDIO() const { 4489 const uint32_t idx = ePropertyDisableSTDIO; 4490 return GetPropertyAtIndexAs<bool>( 4491 idx, g_target_properties[idx].default_uint_value != 0); 4492 } 4493 4494 void TargetProperties::SetDisableSTDIO(bool b) { 4495 const uint32_t idx = ePropertyDisableSTDIO; 4496 SetPropertyAtIndex(idx, b); 4497 } 4498 llvm::StringRef TargetProperties::GetLaunchWorkingDirectory() const { 4499 const uint32_t idx = ePropertyLaunchWorkingDir; 4500 return GetPropertyAtIndexAs<llvm::StringRef>( 4501 idx, g_target_properties[idx].default_cstr_value); 4502 } 4503 4504 const char *TargetProperties::GetDisassemblyFlavor() const { 4505 const uint32_t idx = ePropertyDisassemblyFlavor; 4506 const char *return_value; 4507 4508 x86DisassemblyFlavor flavor_value = 4509 GetPropertyAtIndexAs<x86DisassemblyFlavor>( 4510 idx, static_cast<x86DisassemblyFlavor>( 4511 g_target_properties[idx].default_uint_value)); 4512 4513 return_value = g_x86_dis_flavor_value_types[flavor_value].string_value; 4514 return return_value; 4515 } 4516 4517 const char *TargetProperties::GetDisassemblyCPU() const { 4518 const uint32_t idx = ePropertyDisassemblyCPU; 4519 llvm::StringRef str = GetPropertyAtIndexAs<llvm::StringRef>( 4520 idx, g_target_properties[idx].default_cstr_value); 4521 return str.empty() ? nullptr : str.data(); 4522 } 4523 4524 const char *TargetProperties::GetDisassemblyFeatures() const { 4525 const uint32_t idx = ePropertyDisassemblyFeatures; 4526 llvm::StringRef str = GetPropertyAtIndexAs<llvm::StringRef>( 4527 idx, g_target_properties[idx].default_cstr_value); 4528 return str.empty() ? nullptr : str.data(); 4529 } 4530 4531 InlineStrategy TargetProperties::GetInlineStrategy() const { 4532 const uint32_t idx = ePropertyInlineStrategy; 4533 return GetPropertyAtIndexAs<InlineStrategy>( 4534 idx, 4535 static_cast<InlineStrategy>(g_target_properties[idx].default_uint_value)); 4536 } 4537 4538 // Returning RealpathPrefixes, but the setting's type is FileSpecList. We do 4539 // this because we want the FileSpecList to normalize the file paths for us. 4540 RealpathPrefixes TargetProperties::GetSourceRealpathPrefixes() const { 4541 const uint32_t idx = ePropertySourceRealpathPrefixes; 4542 return RealpathPrefixes(GetPropertyAtIndexAs<FileSpecList>(idx, {})); 4543 } 4544 4545 llvm::StringRef TargetProperties::GetArg0() const { 4546 const uint32_t idx = ePropertyArg0; 4547 return GetPropertyAtIndexAs<llvm::StringRef>( 4548 idx, g_target_properties[idx].default_cstr_value); 4549 } 4550 4551 void TargetProperties::SetArg0(llvm::StringRef arg) { 4552 const uint32_t idx = ePropertyArg0; 4553 SetPropertyAtIndex(idx, arg); 4554 m_launch_info.SetArg0(arg); 4555 } 4556 4557 bool TargetProperties::GetRunArguments(Args &args) const { 4558 const uint32_t idx = ePropertyRunArgs; 4559 return m_collection_sp->GetPropertyAtIndexAsArgs(idx, args); 4560 } 4561 4562 void TargetProperties::SetRunArguments(const Args &args) { 4563 const uint32_t idx = ePropertyRunArgs; 4564 m_collection_sp->SetPropertyAtIndexFromArgs(idx, args); 4565 m_launch_info.GetArguments() = args; 4566 } 4567 4568 Environment TargetProperties::ComputeEnvironment() const { 4569 Environment env; 4570 4571 if (m_target && 4572 GetPropertyAtIndexAs<bool>( 4573 ePropertyInheritEnv, 4574 g_target_properties[ePropertyInheritEnv].default_uint_value != 0)) { 4575 if (auto platform_sp = m_target->GetPlatform()) { 4576 Environment platform_env = platform_sp->GetEnvironment(); 4577 for (const auto &KV : platform_env) 4578 env[KV.first()] = KV.second; 4579 } 4580 } 4581 4582 Args property_unset_env; 4583 m_collection_sp->GetPropertyAtIndexAsArgs(ePropertyUnsetEnvVars, 4584 property_unset_env); 4585 for (const auto &var : property_unset_env) 4586 env.erase(var.ref()); 4587 4588 Args property_env; 4589 m_collection_sp->GetPropertyAtIndexAsArgs(ePropertyEnvVars, property_env); 4590 for (const auto &KV : Environment(property_env)) 4591 env[KV.first()] = KV.second; 4592 4593 return env; 4594 } 4595 4596 Environment TargetProperties::GetEnvironment() const { 4597 return ComputeEnvironment(); 4598 } 4599 4600 Environment TargetProperties::GetInheritedEnvironment() const { 4601 Environment environment; 4602 4603 if (m_target == nullptr) 4604 return environment; 4605 4606 if (!GetPropertyAtIndexAs<bool>( 4607 ePropertyInheritEnv, 4608 g_target_properties[ePropertyInheritEnv].default_uint_value != 0)) 4609 return environment; 4610 4611 PlatformSP platform_sp = m_target->GetPlatform(); 4612 if (platform_sp == nullptr) 4613 return environment; 4614 4615 Environment platform_environment = platform_sp->GetEnvironment(); 4616 for (const auto &KV : platform_environment) 4617 environment[KV.first()] = KV.second; 4618 4619 Args property_unset_environment; 4620 m_collection_sp->GetPropertyAtIndexAsArgs(ePropertyUnsetEnvVars, 4621 property_unset_environment); 4622 for (const auto &var : property_unset_environment) 4623 environment.erase(var.ref()); 4624 4625 return environment; 4626 } 4627 4628 Environment TargetProperties::GetTargetEnvironment() const { 4629 Args property_environment; 4630 m_collection_sp->GetPropertyAtIndexAsArgs(ePropertyEnvVars, 4631 property_environment); 4632 Environment environment; 4633 for (const auto &KV : Environment(property_environment)) 4634 environment[KV.first()] = KV.second; 4635 4636 return environment; 4637 } 4638 4639 void TargetProperties::SetEnvironment(Environment env) { 4640 // TODO: Get rid of the Args intermediate step 4641 const uint32_t idx = ePropertyEnvVars; 4642 m_collection_sp->SetPropertyAtIndexFromArgs(idx, Args(env)); 4643 } 4644 4645 bool TargetProperties::GetSkipPrologue() const { 4646 const uint32_t idx = ePropertySkipPrologue; 4647 return GetPropertyAtIndexAs<bool>( 4648 idx, g_target_properties[idx].default_uint_value != 0); 4649 } 4650 4651 PathMappingList &TargetProperties::GetSourcePathMap() const { 4652 const uint32_t idx = ePropertySourceMap; 4653 OptionValuePathMappings *option_value = 4654 m_collection_sp->GetPropertyAtIndexAsOptionValuePathMappings(idx); 4655 assert(option_value); 4656 return option_value->GetCurrentValue(); 4657 } 4658 4659 PathMappingList &TargetProperties::GetObjectPathMap() const { 4660 const uint32_t idx = ePropertyObjectMap; 4661 OptionValuePathMappings *option_value = 4662 m_collection_sp->GetPropertyAtIndexAsOptionValuePathMappings(idx); 4663 assert(option_value); 4664 return option_value->GetCurrentValue(); 4665 } 4666 4667 bool TargetProperties::GetAutoSourceMapRelative() const { 4668 const uint32_t idx = ePropertyAutoSourceMapRelative; 4669 return GetPropertyAtIndexAs<bool>( 4670 idx, g_target_properties[idx].default_uint_value != 0); 4671 } 4672 4673 void TargetProperties::AppendExecutableSearchPaths(const FileSpec &dir) { 4674 const uint32_t idx = ePropertyExecutableSearchPaths; 4675 OptionValueFileSpecList *option_value = 4676 m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(idx); 4677 assert(option_value); 4678 option_value->AppendCurrentValue(dir); 4679 } 4680 4681 FileSpecList TargetProperties::GetExecutableSearchPaths() { 4682 const uint32_t idx = ePropertyExecutableSearchPaths; 4683 return GetPropertyAtIndexAs<FileSpecList>(idx, {}); 4684 } 4685 4686 FileSpecList TargetProperties::GetDebugFileSearchPaths() { 4687 const uint32_t idx = ePropertyDebugFileSearchPaths; 4688 return GetPropertyAtIndexAs<FileSpecList>(idx, {}); 4689 } 4690 4691 FileSpecList TargetProperties::GetClangModuleSearchPaths() { 4692 const uint32_t idx = ePropertyClangModuleSearchPaths; 4693 return GetPropertyAtIndexAs<FileSpecList>(idx, {}); 4694 } 4695 4696 bool TargetProperties::GetEnableAutoImportClangModules() const { 4697 const uint32_t idx = ePropertyAutoImportClangModules; 4698 return GetPropertyAtIndexAs<bool>( 4699 idx, g_target_properties[idx].default_uint_value != 0); 4700 } 4701 4702 ImportStdModule TargetProperties::GetImportStdModule() const { 4703 const uint32_t idx = ePropertyImportStdModule; 4704 return GetPropertyAtIndexAs<ImportStdModule>( 4705 idx, static_cast<ImportStdModule>( 4706 g_target_properties[idx].default_uint_value)); 4707 } 4708 4709 DynamicClassInfoHelper TargetProperties::GetDynamicClassInfoHelper() const { 4710 const uint32_t idx = ePropertyDynamicClassInfoHelper; 4711 return GetPropertyAtIndexAs<DynamicClassInfoHelper>( 4712 idx, static_cast<DynamicClassInfoHelper>( 4713 g_target_properties[idx].default_uint_value)); 4714 } 4715 4716 bool TargetProperties::GetEnableAutoApplyFixIts() const { 4717 const uint32_t idx = ePropertyAutoApplyFixIts; 4718 return GetPropertyAtIndexAs<bool>( 4719 idx, g_target_properties[idx].default_uint_value != 0); 4720 } 4721 4722 uint64_t TargetProperties::GetNumberOfRetriesWithFixits() const { 4723 const uint32_t idx = ePropertyRetriesWithFixIts; 4724 return GetPropertyAtIndexAs<uint64_t>( 4725 idx, g_target_properties[idx].default_uint_value); 4726 } 4727 4728 bool TargetProperties::GetEnableNotifyAboutFixIts() const { 4729 const uint32_t idx = ePropertyNotifyAboutFixIts; 4730 return GetPropertyAtIndexAs<bool>( 4731 idx, g_target_properties[idx].default_uint_value != 0); 4732 } 4733 4734 FileSpec TargetProperties::GetSaveJITObjectsDir() const { 4735 const uint32_t idx = ePropertySaveObjectsDir; 4736 return GetPropertyAtIndexAs<FileSpec>(idx, {}); 4737 } 4738 4739 void TargetProperties::CheckJITObjectsDir() { 4740 FileSpec new_dir = GetSaveJITObjectsDir(); 4741 if (!new_dir) 4742 return; 4743 4744 const FileSystem &instance = FileSystem::Instance(); 4745 bool exists = instance.Exists(new_dir); 4746 bool is_directory = instance.IsDirectory(new_dir); 4747 std::string path = new_dir.GetPath(true); 4748 bool writable = llvm::sys::fs::can_write(path); 4749 if (exists && is_directory && writable) 4750 return; 4751 4752 m_collection_sp->GetPropertyAtIndex(ePropertySaveObjectsDir) 4753 ->GetValue() 4754 ->Clear(); 4755 4756 std::string buffer; 4757 llvm::raw_string_ostream os(buffer); 4758 os << "JIT object dir '" << path << "' "; 4759 if (!exists) 4760 os << "does not exist"; 4761 else if (!is_directory) 4762 os << "is not a directory"; 4763 else if (!writable) 4764 os << "is not writable"; 4765 4766 std::optional<lldb::user_id_t> debugger_id; 4767 if (m_target) 4768 debugger_id = m_target->GetDebugger().GetID(); 4769 Debugger::ReportError(buffer, debugger_id); 4770 } 4771 4772 bool TargetProperties::GetEnableSyntheticValue() const { 4773 const uint32_t idx = ePropertyEnableSynthetic; 4774 return GetPropertyAtIndexAs<bool>( 4775 idx, g_target_properties[idx].default_uint_value != 0); 4776 } 4777 4778 bool TargetProperties::ShowHexVariableValuesWithLeadingZeroes() const { 4779 const uint32_t idx = ePropertyShowHexVariableValuesWithLeadingZeroes; 4780 return GetPropertyAtIndexAs<bool>( 4781 idx, g_target_properties[idx].default_uint_value != 0); 4782 } 4783 4784 uint32_t TargetProperties::GetMaxZeroPaddingInFloatFormat() const { 4785 const uint32_t idx = ePropertyMaxZeroPaddingInFloatFormat; 4786 return GetPropertyAtIndexAs<uint64_t>( 4787 idx, g_target_properties[idx].default_uint_value); 4788 } 4789 4790 uint32_t TargetProperties::GetMaximumNumberOfChildrenToDisplay() const { 4791 const uint32_t idx = ePropertyMaxChildrenCount; 4792 return GetPropertyAtIndexAs<uint64_t>( 4793 idx, g_target_properties[idx].default_uint_value); 4794 } 4795 4796 std::pair<uint32_t, bool> 4797 TargetProperties::GetMaximumDepthOfChildrenToDisplay() const { 4798 const uint32_t idx = ePropertyMaxChildrenDepth; 4799 auto *option_value = 4800 m_collection_sp->GetPropertyAtIndexAsOptionValueUInt64(idx); 4801 bool is_default = !option_value->OptionWasSet(); 4802 return {option_value->GetCurrentValue(), is_default}; 4803 } 4804 4805 uint32_t TargetProperties::GetMaximumSizeOfStringSummary() const { 4806 const uint32_t idx = ePropertyMaxSummaryLength; 4807 return GetPropertyAtIndexAs<uint64_t>( 4808 idx, g_target_properties[idx].default_uint_value); 4809 } 4810 4811 uint32_t TargetProperties::GetMaximumMemReadSize() const { 4812 const uint32_t idx = ePropertyMaxMemReadSize; 4813 return GetPropertyAtIndexAs<uint64_t>( 4814 idx, g_target_properties[idx].default_uint_value); 4815 } 4816 4817 FileSpec TargetProperties::GetStandardInputPath() const { 4818 const uint32_t idx = ePropertyInputPath; 4819 return GetPropertyAtIndexAs<FileSpec>(idx, {}); 4820 } 4821 4822 void TargetProperties::SetStandardInputPath(llvm::StringRef path) { 4823 const uint32_t idx = ePropertyInputPath; 4824 SetPropertyAtIndex(idx, path); 4825 } 4826 4827 FileSpec TargetProperties::GetStandardOutputPath() const { 4828 const uint32_t idx = ePropertyOutputPath; 4829 return GetPropertyAtIndexAs<FileSpec>(idx, {}); 4830 } 4831 4832 void TargetProperties::SetStandardOutputPath(llvm::StringRef path) { 4833 const uint32_t idx = ePropertyOutputPath; 4834 SetPropertyAtIndex(idx, path); 4835 } 4836 4837 FileSpec TargetProperties::GetStandardErrorPath() const { 4838 const uint32_t idx = ePropertyErrorPath; 4839 return GetPropertyAtIndexAs<FileSpec>(idx, {}); 4840 } 4841 4842 void TargetProperties::SetStandardErrorPath(llvm::StringRef path) { 4843 const uint32_t idx = ePropertyErrorPath; 4844 SetPropertyAtIndex(idx, path); 4845 } 4846 4847 SourceLanguage TargetProperties::GetLanguage() const { 4848 const uint32_t idx = ePropertyLanguage; 4849 return {GetPropertyAtIndexAs<LanguageType>(idx, {})}; 4850 } 4851 4852 llvm::StringRef TargetProperties::GetExpressionPrefixContents() { 4853 const uint32_t idx = ePropertyExprPrefix; 4854 OptionValueFileSpec *file = 4855 m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpec(idx); 4856 if (file) { 4857 DataBufferSP data_sp(file->GetFileContents()); 4858 if (data_sp) 4859 return llvm::StringRef( 4860 reinterpret_cast<const char *>(data_sp->GetBytes()), 4861 data_sp->GetByteSize()); 4862 } 4863 return ""; 4864 } 4865 4866 uint64_t TargetProperties::GetExprErrorLimit() const { 4867 const uint32_t idx = ePropertyExprErrorLimit; 4868 return GetPropertyAtIndexAs<uint64_t>( 4869 idx, g_target_properties[idx].default_uint_value); 4870 } 4871 4872 uint64_t TargetProperties::GetExprAllocAddress() const { 4873 const uint32_t idx = ePropertyExprAllocAddress; 4874 return GetPropertyAtIndexAs<uint64_t>( 4875 idx, g_target_properties[idx].default_uint_value); 4876 } 4877 4878 uint64_t TargetProperties::GetExprAllocSize() const { 4879 const uint32_t idx = ePropertyExprAllocSize; 4880 return GetPropertyAtIndexAs<uint64_t>( 4881 idx, g_target_properties[idx].default_uint_value); 4882 } 4883 4884 uint64_t TargetProperties::GetExprAllocAlign() const { 4885 const uint32_t idx = ePropertyExprAllocAlign; 4886 return GetPropertyAtIndexAs<uint64_t>( 4887 idx, g_target_properties[idx].default_uint_value); 4888 } 4889 4890 bool TargetProperties::GetBreakpointsConsultPlatformAvoidList() { 4891 const uint32_t idx = ePropertyBreakpointUseAvoidList; 4892 return GetPropertyAtIndexAs<bool>( 4893 idx, g_target_properties[idx].default_uint_value != 0); 4894 } 4895 4896 bool TargetProperties::GetUseHexImmediates() const { 4897 const uint32_t idx = ePropertyUseHexImmediates; 4898 return GetPropertyAtIndexAs<bool>( 4899 idx, g_target_properties[idx].default_uint_value != 0); 4900 } 4901 4902 bool TargetProperties::GetUseFastStepping() const { 4903 const uint32_t idx = ePropertyUseFastStepping; 4904 return GetPropertyAtIndexAs<bool>( 4905 idx, g_target_properties[idx].default_uint_value != 0); 4906 } 4907 4908 bool TargetProperties::GetDisplayExpressionsInCrashlogs() const { 4909 const uint32_t idx = ePropertyDisplayExpressionsInCrashlogs; 4910 return GetPropertyAtIndexAs<bool>( 4911 idx, g_target_properties[idx].default_uint_value != 0); 4912 } 4913 4914 LoadScriptFromSymFile TargetProperties::GetLoadScriptFromSymbolFile() const { 4915 const uint32_t idx = ePropertyLoadScriptFromSymbolFile; 4916 return GetPropertyAtIndexAs<LoadScriptFromSymFile>( 4917 idx, static_cast<LoadScriptFromSymFile>( 4918 g_target_properties[idx].default_uint_value)); 4919 } 4920 4921 LoadCWDlldbinitFile TargetProperties::GetLoadCWDlldbinitFile() const { 4922 const uint32_t idx = ePropertyLoadCWDlldbinitFile; 4923 return GetPropertyAtIndexAs<LoadCWDlldbinitFile>( 4924 idx, static_cast<LoadCWDlldbinitFile>( 4925 g_target_properties[idx].default_uint_value)); 4926 } 4927 4928 Disassembler::HexImmediateStyle TargetProperties::GetHexImmediateStyle() const { 4929 const uint32_t idx = ePropertyHexImmediateStyle; 4930 return GetPropertyAtIndexAs<Disassembler::HexImmediateStyle>( 4931 idx, static_cast<Disassembler::HexImmediateStyle>( 4932 g_target_properties[idx].default_uint_value)); 4933 } 4934 4935 MemoryModuleLoadLevel TargetProperties::GetMemoryModuleLoadLevel() const { 4936 const uint32_t idx = ePropertyMemoryModuleLoadLevel; 4937 return GetPropertyAtIndexAs<MemoryModuleLoadLevel>( 4938 idx, static_cast<MemoryModuleLoadLevel>( 4939 g_target_properties[idx].default_uint_value)); 4940 } 4941 4942 bool TargetProperties::GetUserSpecifiedTrapHandlerNames(Args &args) const { 4943 const uint32_t idx = ePropertyTrapHandlerNames; 4944 return m_collection_sp->GetPropertyAtIndexAsArgs(idx, args); 4945 } 4946 4947 void TargetProperties::SetUserSpecifiedTrapHandlerNames(const Args &args) { 4948 const uint32_t idx = ePropertyTrapHandlerNames; 4949 m_collection_sp->SetPropertyAtIndexFromArgs(idx, args); 4950 } 4951 4952 bool TargetProperties::GetDisplayRuntimeSupportValues() const { 4953 const uint32_t idx = ePropertyDisplayRuntimeSupportValues; 4954 return GetPropertyAtIndexAs<bool>( 4955 idx, g_target_properties[idx].default_uint_value != 0); 4956 } 4957 4958 void TargetProperties::SetDisplayRuntimeSupportValues(bool b) { 4959 const uint32_t idx = ePropertyDisplayRuntimeSupportValues; 4960 SetPropertyAtIndex(idx, b); 4961 } 4962 4963 bool TargetProperties::GetDisplayRecognizedArguments() const { 4964 const uint32_t idx = ePropertyDisplayRecognizedArguments; 4965 return GetPropertyAtIndexAs<bool>( 4966 idx, g_target_properties[idx].default_uint_value != 0); 4967 } 4968 4969 void TargetProperties::SetDisplayRecognizedArguments(bool b) { 4970 const uint32_t idx = ePropertyDisplayRecognizedArguments; 4971 SetPropertyAtIndex(idx, b); 4972 } 4973 4974 const ProcessLaunchInfo &TargetProperties::GetProcessLaunchInfo() const { 4975 return m_launch_info; 4976 } 4977 4978 void TargetProperties::SetProcessLaunchInfo( 4979 const ProcessLaunchInfo &launch_info) { 4980 m_launch_info = launch_info; 4981 SetArg0(launch_info.GetArg0()); 4982 SetRunArguments(launch_info.GetArguments()); 4983 SetEnvironment(launch_info.GetEnvironment()); 4984 const FileAction *input_file_action = 4985 launch_info.GetFileActionForFD(STDIN_FILENO); 4986 if (input_file_action) { 4987 SetStandardInputPath(input_file_action->GetPath()); 4988 } 4989 const FileAction *output_file_action = 4990 launch_info.GetFileActionForFD(STDOUT_FILENO); 4991 if (output_file_action) { 4992 SetStandardOutputPath(output_file_action->GetPath()); 4993 } 4994 const FileAction *error_file_action = 4995 launch_info.GetFileActionForFD(STDERR_FILENO); 4996 if (error_file_action) { 4997 SetStandardErrorPath(error_file_action->GetPath()); 4998 } 4999 SetDetachOnError(launch_info.GetFlags().Test(lldb::eLaunchFlagDetachOnError)); 5000 SetDisableASLR(launch_info.GetFlags().Test(lldb::eLaunchFlagDisableASLR)); 5001 SetInheritTCC( 5002 launch_info.GetFlags().Test(lldb::eLaunchFlagInheritTCCFromParent)); 5003 SetDisableSTDIO(launch_info.GetFlags().Test(lldb::eLaunchFlagDisableSTDIO)); 5004 } 5005 5006 bool TargetProperties::GetRequireHardwareBreakpoints() const { 5007 const uint32_t idx = ePropertyRequireHardwareBreakpoints; 5008 return GetPropertyAtIndexAs<bool>( 5009 idx, g_target_properties[idx].default_uint_value != 0); 5010 } 5011 5012 void TargetProperties::SetRequireHardwareBreakpoints(bool b) { 5013 const uint32_t idx = ePropertyRequireHardwareBreakpoints; 5014 m_collection_sp->SetPropertyAtIndex(idx, b); 5015 } 5016 5017 bool TargetProperties::GetAutoInstallMainExecutable() const { 5018 const uint32_t idx = ePropertyAutoInstallMainExecutable; 5019 return GetPropertyAtIndexAs<bool>( 5020 idx, g_target_properties[idx].default_uint_value != 0); 5021 } 5022 5023 void TargetProperties::Arg0ValueChangedCallback() { 5024 m_launch_info.SetArg0(GetArg0()); 5025 } 5026 5027 void TargetProperties::RunArgsValueChangedCallback() { 5028 Args args; 5029 if (GetRunArguments(args)) 5030 m_launch_info.GetArguments() = args; 5031 } 5032 5033 void TargetProperties::EnvVarsValueChangedCallback() { 5034 m_launch_info.GetEnvironment() = ComputeEnvironment(); 5035 } 5036 5037 void TargetProperties::InputPathValueChangedCallback() { 5038 m_launch_info.AppendOpenFileAction(STDIN_FILENO, GetStandardInputPath(), true, 5039 false); 5040 } 5041 5042 void TargetProperties::OutputPathValueChangedCallback() { 5043 m_launch_info.AppendOpenFileAction(STDOUT_FILENO, GetStandardOutputPath(), 5044 false, true); 5045 } 5046 5047 void TargetProperties::ErrorPathValueChangedCallback() { 5048 m_launch_info.AppendOpenFileAction(STDERR_FILENO, GetStandardErrorPath(), 5049 false, true); 5050 } 5051 5052 void TargetProperties::DetachOnErrorValueChangedCallback() { 5053 if (GetDetachOnError()) 5054 m_launch_info.GetFlags().Set(lldb::eLaunchFlagDetachOnError); 5055 else 5056 m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDetachOnError); 5057 } 5058 5059 void TargetProperties::DisableASLRValueChangedCallback() { 5060 if (GetDisableASLR()) 5061 m_launch_info.GetFlags().Set(lldb::eLaunchFlagDisableASLR); 5062 else 5063 m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDisableASLR); 5064 } 5065 5066 void TargetProperties::InheritTCCValueChangedCallback() { 5067 if (GetInheritTCC()) 5068 m_launch_info.GetFlags().Set(lldb::eLaunchFlagInheritTCCFromParent); 5069 else 5070 m_launch_info.GetFlags().Clear(lldb::eLaunchFlagInheritTCCFromParent); 5071 } 5072 5073 void TargetProperties::DisableSTDIOValueChangedCallback() { 5074 if (GetDisableSTDIO()) 5075 m_launch_info.GetFlags().Set(lldb::eLaunchFlagDisableSTDIO); 5076 else 5077 m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDisableSTDIO); 5078 } 5079 5080 bool TargetProperties::GetDebugUtilityExpression() const { 5081 const uint32_t idx = ePropertyDebugUtilityExpression; 5082 return GetPropertyAtIndexAs<bool>( 5083 idx, g_target_properties[idx].default_uint_value != 0); 5084 } 5085 5086 void TargetProperties::SetDebugUtilityExpression(bool debug) { 5087 const uint32_t idx = ePropertyDebugUtilityExpression; 5088 SetPropertyAtIndex(idx, debug); 5089 } 5090 5091 // Target::TargetEventData 5092 5093 Target::TargetEventData::TargetEventData(const lldb::TargetSP &target_sp) 5094 : EventData(), m_target_sp(target_sp), m_module_list() {} 5095 5096 Target::TargetEventData::TargetEventData(const lldb::TargetSP &target_sp, 5097 const ModuleList &module_list) 5098 : EventData(), m_target_sp(target_sp), m_module_list(module_list) {} 5099 5100 Target::TargetEventData::~TargetEventData() = default; 5101 5102 llvm::StringRef Target::TargetEventData::GetFlavorString() { 5103 return "Target::TargetEventData"; 5104 } 5105 5106 void Target::TargetEventData::Dump(Stream *s) const { 5107 for (size_t i = 0; i < m_module_list.GetSize(); ++i) { 5108 if (i != 0) 5109 *s << ", "; 5110 m_module_list.GetModuleAtIndex(i)->GetDescription( 5111 s->AsRawOstream(), lldb::eDescriptionLevelBrief); 5112 } 5113 } 5114 5115 const Target::TargetEventData * 5116 Target::TargetEventData::GetEventDataFromEvent(const Event *event_ptr) { 5117 if (event_ptr) { 5118 const EventData *event_data = event_ptr->GetData(); 5119 if (event_data && 5120 event_data->GetFlavor() == TargetEventData::GetFlavorString()) 5121 return static_cast<const TargetEventData *>(event_ptr->GetData()); 5122 } 5123 return nullptr; 5124 } 5125 5126 TargetSP Target::TargetEventData::GetTargetFromEvent(const Event *event_ptr) { 5127 TargetSP target_sp; 5128 const TargetEventData *event_data = GetEventDataFromEvent(event_ptr); 5129 if (event_data) 5130 target_sp = event_data->m_target_sp; 5131 return target_sp; 5132 } 5133 5134 ModuleList 5135 Target::TargetEventData::GetModuleListFromEvent(const Event *event_ptr) { 5136 ModuleList module_list; 5137 const TargetEventData *event_data = GetEventDataFromEvent(event_ptr); 5138 if (event_data) 5139 module_list = event_data->m_module_list; 5140 return module_list; 5141 } 5142 5143 std::recursive_mutex &Target::GetAPIMutex() { 5144 if (GetProcessSP() && GetProcessSP()->CurrentThreadIsPrivateStateThread()) 5145 return m_private_mutex; 5146 else 5147 return m_mutex; 5148 } 5149 5150 /// Get metrics associated with this target in JSON format. 5151 llvm::json::Value 5152 Target::ReportStatistics(const lldb_private::StatisticsOptions &options) { 5153 return m_stats.ToJSON(*this, options); 5154 } 5155 5156 void Target::ResetStatistics() { m_stats.Reset(*this); } 5157 5158 bool Target::HasLoadedSections() { return !GetSectionLoadList().IsEmpty(); } 5159 5160 lldb::addr_t Target::GetSectionLoadAddress(const lldb::SectionSP §ion_sp) { 5161 return GetSectionLoadList().GetSectionLoadAddress(section_sp); 5162 } 5163 5164 void Target::ClearSectionLoadList() { GetSectionLoadList().Clear(); } 5165 5166 void Target::DumpSectionLoadList(Stream &s) { 5167 GetSectionLoadList().Dump(s, this); 5168 } 5169