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