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