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