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