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