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