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