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 BroadcastEvent(eBroadcastBitModulesUnloaded, 1646 new TargetEventData(this->shared_from_this(), module_list)); 1647 m_breakpoint_list.UpdateBreakpoints(module_list, false, delete_locations); 1648 m_internal_breakpoint_list.UpdateBreakpoints(module_list, false, 1649 delete_locations); 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 // Hijacking events of the process to be created to be sure that all events 3030 // until the first stop are intercepted (in case if platform doesn't define 3031 // its own hijacking listener or if the process is created by the target 3032 // manually, without the platform). 3033 if (!launch_info.GetHijackListener()) 3034 launch_info.SetHijackListener( 3035 Listener::MakeListener("lldb.Target.Launch.hijack")); 3036 3037 // If we're not already connected to the process, and if we have a platform 3038 // that can launch a process for debugging, go ahead and do that here. 3039 if (state != eStateConnected && platform_sp && 3040 platform_sp->CanDebugProcess() && !launch_info.IsScriptedProcess()) { 3041 LLDB_LOGF(log, "Target::%s asking the platform to debug the process", 3042 __FUNCTION__); 3043 3044 // If there was a previous process, delete it before we make the new one. 3045 // One subtle point, we delete the process before we release the reference 3046 // to m_process_sp. That way even if we are the last owner, the process 3047 // will get Finalized before it gets destroyed. 3048 DeleteCurrentProcess(); 3049 3050 m_process_sp = 3051 GetPlatform()->DebugProcess(launch_info, debugger, *this, error); 3052 3053 } else { 3054 LLDB_LOGF(log, 3055 "Target::%s the platform doesn't know how to debug a " 3056 "process, getting a process plugin to do this for us.", 3057 __FUNCTION__); 3058 3059 if (state == eStateConnected) { 3060 assert(m_process_sp); 3061 } else { 3062 // Use a Process plugin to construct the process. 3063 const char *plugin_name = launch_info.GetProcessPluginName(); 3064 CreateProcess(launch_info.GetListener(), plugin_name, nullptr, false); 3065 } 3066 3067 // Since we didn't have a platform launch the process, launch it here. 3068 if (m_process_sp) { 3069 m_process_sp->HijackProcessEvents(launch_info.GetHijackListener()); 3070 error = m_process_sp->Launch(launch_info); 3071 } 3072 } 3073 3074 if (!m_process_sp && error.Success()) 3075 error.SetErrorString("failed to launch or debug process"); 3076 3077 if (!error.Success()) 3078 return error; 3079 3080 bool rebroadcast_first_stop = 3081 !synchronous_execution && 3082 launch_info.GetFlags().Test(eLaunchFlagStopAtEntry); 3083 3084 assert(launch_info.GetHijackListener()); 3085 3086 EventSP first_stop_event_sp; 3087 state = m_process_sp->WaitForProcessToStop(llvm::None, &first_stop_event_sp, 3088 rebroadcast_first_stop, 3089 launch_info.GetHijackListener()); 3090 m_process_sp->RestoreProcessEvents(); 3091 3092 if (rebroadcast_first_stop) { 3093 assert(first_stop_event_sp); 3094 m_process_sp->BroadcastEvent(first_stop_event_sp); 3095 return error; 3096 } 3097 3098 switch (state) { 3099 case eStateStopped: { 3100 if (launch_info.GetFlags().Test(eLaunchFlagStopAtEntry)) 3101 break; 3102 if (synchronous_execution) 3103 // Now we have handled the stop-from-attach, and we are just 3104 // switching to a synchronous resume. So we should switch to the 3105 // SyncResume hijacker. 3106 m_process_sp->ResumeSynchronous(stream); 3107 else 3108 error = m_process_sp->PrivateResume(); 3109 if (!error.Success()) { 3110 Status error2; 3111 error2.SetErrorStringWithFormat( 3112 "process resume at entry point failed: %s", error.AsCString()); 3113 error = error2; 3114 } 3115 } break; 3116 case eStateExited: { 3117 bool with_shell = !!launch_info.GetShell(); 3118 const int exit_status = m_process_sp->GetExitStatus(); 3119 const char *exit_desc = m_process_sp->GetExitDescription(); 3120 std::string desc; 3121 if (exit_desc && exit_desc[0]) 3122 desc = " (" + std::string(exit_desc) + ')'; 3123 if (with_shell) 3124 error.SetErrorStringWithFormat( 3125 "process exited with status %i%s\n" 3126 "'r' and 'run' are aliases that default to launching through a " 3127 "shell.\n" 3128 "Try launching without going through a shell by using " 3129 "'process launch'.", 3130 exit_status, desc.c_str()); 3131 else 3132 error.SetErrorStringWithFormat("process exited with status %i%s", 3133 exit_status, desc.c_str()); 3134 } break; 3135 default: 3136 error.SetErrorStringWithFormat("initial process state wasn't stopped: %s", 3137 StateAsCString(state)); 3138 break; 3139 } 3140 return error; 3141 } 3142 3143 void Target::SetTrace(const TraceSP &trace_sp) { m_trace_sp = trace_sp; } 3144 3145 TraceSP Target::GetTrace() { return m_trace_sp; } 3146 3147 llvm::Expected<TraceSP> Target::CreateTrace() { 3148 if (!m_process_sp) 3149 return llvm::createStringError(llvm::inconvertibleErrorCode(), 3150 "A process is required for tracing"); 3151 if (m_trace_sp) 3152 return llvm::createStringError(llvm::inconvertibleErrorCode(), 3153 "A trace already exists for the target"); 3154 3155 llvm::Expected<TraceSupportedResponse> trace_type = 3156 m_process_sp->TraceSupported(); 3157 if (!trace_type) 3158 return llvm::createStringError( 3159 llvm::inconvertibleErrorCode(), "Tracing is not supported. %s", 3160 llvm::toString(trace_type.takeError()).c_str()); 3161 if (llvm::Expected<TraceSP> trace_sp = 3162 Trace::FindPluginForLiveProcess(trace_type->name, *m_process_sp)) 3163 m_trace_sp = *trace_sp; 3164 else 3165 return llvm::createStringError( 3166 llvm::inconvertibleErrorCode(), 3167 "Couldn't create a Trace object for the process. %s", 3168 llvm::toString(trace_sp.takeError()).c_str()); 3169 return m_trace_sp; 3170 } 3171 3172 llvm::Expected<TraceSP> Target::GetTraceOrCreate() { 3173 if (m_trace_sp) 3174 return m_trace_sp; 3175 return CreateTrace(); 3176 } 3177 3178 Status Target::Attach(ProcessAttachInfo &attach_info, Stream *stream) { 3179 m_stats.SetLaunchOrAttachTime(); 3180 auto state = eStateInvalid; 3181 auto process_sp = GetProcessSP(); 3182 if (process_sp) { 3183 state = process_sp->GetState(); 3184 if (process_sp->IsAlive() && state != eStateConnected) { 3185 if (state == eStateAttaching) 3186 return Status("process attach is in progress"); 3187 return Status("a process is already being debugged"); 3188 } 3189 } 3190 3191 const ModuleSP old_exec_module_sp = GetExecutableModule(); 3192 3193 // If no process info was specified, then use the target executable name as 3194 // the process to attach to by default 3195 if (!attach_info.ProcessInfoSpecified()) { 3196 if (old_exec_module_sp) 3197 attach_info.GetExecutableFile().GetFilename() = 3198 old_exec_module_sp->GetPlatformFileSpec().GetFilename(); 3199 3200 if (!attach_info.ProcessInfoSpecified()) { 3201 return Status("no process specified, create a target with a file, or " 3202 "specify the --pid or --name"); 3203 } 3204 } 3205 3206 const auto platform_sp = 3207 GetDebugger().GetPlatformList().GetSelectedPlatform(); 3208 ListenerSP hijack_listener_sp; 3209 const bool async = attach_info.GetAsync(); 3210 if (!async) { 3211 hijack_listener_sp = 3212 Listener::MakeListener("lldb.Target.Attach.attach.hijack"); 3213 attach_info.SetHijackListener(hijack_listener_sp); 3214 } 3215 3216 Status error; 3217 if (state != eStateConnected && platform_sp != nullptr && 3218 platform_sp->CanDebugProcess()) { 3219 SetPlatform(platform_sp); 3220 process_sp = platform_sp->Attach(attach_info, GetDebugger(), this, error); 3221 } else { 3222 if (state != eStateConnected) { 3223 const char *plugin_name = attach_info.GetProcessPluginName(); 3224 process_sp = 3225 CreateProcess(attach_info.GetListenerForProcess(GetDebugger()), 3226 plugin_name, nullptr, false); 3227 if (process_sp == nullptr) { 3228 error.SetErrorStringWithFormat( 3229 "failed to create process using plugin %s", 3230 (plugin_name) ? plugin_name : "null"); 3231 return error; 3232 } 3233 } 3234 if (hijack_listener_sp) 3235 process_sp->HijackProcessEvents(hijack_listener_sp); 3236 error = process_sp->Attach(attach_info); 3237 } 3238 3239 if (error.Success() && process_sp) { 3240 if (async) { 3241 process_sp->RestoreProcessEvents(); 3242 } else { 3243 state = process_sp->WaitForProcessToStop( 3244 llvm::None, nullptr, false, attach_info.GetHijackListener(), stream); 3245 process_sp->RestoreProcessEvents(); 3246 3247 if (state != eStateStopped) { 3248 const char *exit_desc = process_sp->GetExitDescription(); 3249 if (exit_desc) 3250 error.SetErrorStringWithFormat("%s", exit_desc); 3251 else 3252 error.SetErrorString( 3253 "process did not stop (no such process or permission problem?)"); 3254 process_sp->Destroy(false); 3255 } 3256 } 3257 } 3258 return error; 3259 } 3260 3261 void Target::FinalizeFileActions(ProcessLaunchInfo &info) { 3262 Log *log = GetLog(LLDBLog::Process); 3263 3264 // Finalize the file actions, and if none were given, default to opening up a 3265 // pseudo terminal 3266 PlatformSP platform_sp = GetPlatform(); 3267 const bool default_to_use_pty = 3268 m_platform_sp ? m_platform_sp->IsHost() : false; 3269 LLDB_LOG( 3270 log, 3271 "have platform={0}, platform_sp->IsHost()={1}, default_to_use_pty={2}", 3272 bool(platform_sp), 3273 platform_sp ? (platform_sp->IsHost() ? "true" : "false") : "n/a", 3274 default_to_use_pty); 3275 3276 // If nothing for stdin or stdout or stderr was specified, then check the 3277 // process for any default settings that were set with "settings set" 3278 if (info.GetFileActionForFD(STDIN_FILENO) == nullptr || 3279 info.GetFileActionForFD(STDOUT_FILENO) == nullptr || 3280 info.GetFileActionForFD(STDERR_FILENO) == nullptr) { 3281 LLDB_LOG(log, "at least one of stdin/stdout/stderr was not set, evaluating " 3282 "default handling"); 3283 3284 if (info.GetFlags().Test(eLaunchFlagLaunchInTTY)) { 3285 // Do nothing, if we are launching in a remote terminal no file actions 3286 // should be done at all. 3287 return; 3288 } 3289 3290 if (info.GetFlags().Test(eLaunchFlagDisableSTDIO)) { 3291 LLDB_LOG(log, "eLaunchFlagDisableSTDIO set, adding suppression action " 3292 "for stdin, stdout and stderr"); 3293 info.AppendSuppressFileAction(STDIN_FILENO, true, false); 3294 info.AppendSuppressFileAction(STDOUT_FILENO, false, true); 3295 info.AppendSuppressFileAction(STDERR_FILENO, false, true); 3296 } else { 3297 // Check for any values that might have gotten set with any of: (lldb) 3298 // settings set target.input-path (lldb) settings set target.output-path 3299 // (lldb) settings set target.error-path 3300 FileSpec in_file_spec; 3301 FileSpec out_file_spec; 3302 FileSpec err_file_spec; 3303 // Only override with the target settings if we don't already have an 3304 // action for in, out or error 3305 if (info.GetFileActionForFD(STDIN_FILENO) == nullptr) 3306 in_file_spec = GetStandardInputPath(); 3307 if (info.GetFileActionForFD(STDOUT_FILENO) == nullptr) 3308 out_file_spec = GetStandardOutputPath(); 3309 if (info.GetFileActionForFD(STDERR_FILENO) == nullptr) 3310 err_file_spec = GetStandardErrorPath(); 3311 3312 LLDB_LOG(log, "target stdin='{0}', target stdout='{1}', stderr='{1}'", 3313 in_file_spec, out_file_spec, err_file_spec); 3314 3315 if (in_file_spec) { 3316 info.AppendOpenFileAction(STDIN_FILENO, in_file_spec, true, false); 3317 LLDB_LOG(log, "appended stdin open file action for {0}", in_file_spec); 3318 } 3319 3320 if (out_file_spec) { 3321 info.AppendOpenFileAction(STDOUT_FILENO, out_file_spec, false, true); 3322 LLDB_LOG(log, "appended stdout open file action for {0}", 3323 out_file_spec); 3324 } 3325 3326 if (err_file_spec) { 3327 info.AppendOpenFileAction(STDERR_FILENO, err_file_spec, false, true); 3328 LLDB_LOG(log, "appended stderr open file action for {0}", 3329 err_file_spec); 3330 } 3331 3332 if (default_to_use_pty) { 3333 llvm::Error Err = info.SetUpPtyRedirection(); 3334 LLDB_LOG_ERROR(log, std::move(Err), "SetUpPtyRedirection failed: {0}"); 3335 } 3336 } 3337 } 3338 } 3339 3340 // Target::StopHook 3341 Target::StopHook::StopHook(lldb::TargetSP target_sp, lldb::user_id_t uid) 3342 : UserID(uid), m_target_sp(target_sp), m_specifier_sp(), 3343 m_thread_spec_up() {} 3344 3345 Target::StopHook::StopHook(const StopHook &rhs) 3346 : UserID(rhs.GetID()), m_target_sp(rhs.m_target_sp), 3347 m_specifier_sp(rhs.m_specifier_sp), m_thread_spec_up(), 3348 m_active(rhs.m_active), m_auto_continue(rhs.m_auto_continue) { 3349 if (rhs.m_thread_spec_up) 3350 m_thread_spec_up = std::make_unique<ThreadSpec>(*rhs.m_thread_spec_up); 3351 } 3352 3353 void Target::StopHook::SetSpecifier(SymbolContextSpecifier *specifier) { 3354 m_specifier_sp.reset(specifier); 3355 } 3356 3357 void Target::StopHook::SetThreadSpecifier(ThreadSpec *specifier) { 3358 m_thread_spec_up.reset(specifier); 3359 } 3360 3361 bool Target::StopHook::ExecutionContextPasses(const ExecutionContext &exc_ctx) { 3362 SymbolContextSpecifier *specifier = GetSpecifier(); 3363 if (!specifier) 3364 return true; 3365 3366 bool will_run = true; 3367 if (exc_ctx.GetFramePtr()) 3368 will_run = GetSpecifier()->SymbolContextMatches( 3369 exc_ctx.GetFramePtr()->GetSymbolContext(eSymbolContextEverything)); 3370 if (will_run && GetThreadSpecifier() != nullptr) 3371 will_run = 3372 GetThreadSpecifier()->ThreadPassesBasicTests(exc_ctx.GetThreadRef()); 3373 3374 return will_run; 3375 } 3376 3377 void Target::StopHook::GetDescription(Stream *s, 3378 lldb::DescriptionLevel level) const { 3379 3380 // For brief descriptions, only print the subclass description: 3381 if (level == eDescriptionLevelBrief) { 3382 GetSubclassDescription(s, level); 3383 return; 3384 } 3385 3386 unsigned indent_level = s->GetIndentLevel(); 3387 3388 s->SetIndentLevel(indent_level + 2); 3389 3390 s->Printf("Hook: %" PRIu64 "\n", GetID()); 3391 if (m_active) 3392 s->Indent("State: enabled\n"); 3393 else 3394 s->Indent("State: disabled\n"); 3395 3396 if (m_auto_continue) 3397 s->Indent("AutoContinue on\n"); 3398 3399 if (m_specifier_sp) { 3400 s->Indent(); 3401 s->PutCString("Specifier:\n"); 3402 s->SetIndentLevel(indent_level + 4); 3403 m_specifier_sp->GetDescription(s, level); 3404 s->SetIndentLevel(indent_level + 2); 3405 } 3406 3407 if (m_thread_spec_up) { 3408 StreamString tmp; 3409 s->Indent("Thread:\n"); 3410 m_thread_spec_up->GetDescription(&tmp, level); 3411 s->SetIndentLevel(indent_level + 4); 3412 s->Indent(tmp.GetString()); 3413 s->PutCString("\n"); 3414 s->SetIndentLevel(indent_level + 2); 3415 } 3416 GetSubclassDescription(s, level); 3417 } 3418 3419 void Target::StopHookCommandLine::GetSubclassDescription( 3420 Stream *s, lldb::DescriptionLevel level) const { 3421 // The brief description just prints the first command. 3422 if (level == eDescriptionLevelBrief) { 3423 if (m_commands.GetSize() == 1) 3424 s->PutCString(m_commands.GetStringAtIndex(0)); 3425 return; 3426 } 3427 s->Indent("Commands: \n"); 3428 s->SetIndentLevel(s->GetIndentLevel() + 4); 3429 uint32_t num_commands = m_commands.GetSize(); 3430 for (uint32_t i = 0; i < num_commands; i++) { 3431 s->Indent(m_commands.GetStringAtIndex(i)); 3432 s->PutCString("\n"); 3433 } 3434 s->SetIndentLevel(s->GetIndentLevel() - 4); 3435 } 3436 3437 // Target::StopHookCommandLine 3438 void Target::StopHookCommandLine::SetActionFromString(const std::string &string) { 3439 GetCommands().SplitIntoLines(string); 3440 } 3441 3442 void Target::StopHookCommandLine::SetActionFromStrings( 3443 const std::vector<std::string> &strings) { 3444 for (auto string : strings) 3445 GetCommands().AppendString(string.c_str()); 3446 } 3447 3448 Target::StopHook::StopHookResult 3449 Target::StopHookCommandLine::HandleStop(ExecutionContext &exc_ctx, 3450 StreamSP output_sp) { 3451 assert(exc_ctx.GetTargetPtr() && "Can't call PerformAction on a context " 3452 "with no target"); 3453 3454 if (!m_commands.GetSize()) 3455 return StopHookResult::KeepStopped; 3456 3457 CommandReturnObject result(false); 3458 result.SetImmediateOutputStream(output_sp); 3459 result.SetInteractive(false); 3460 Debugger &debugger = exc_ctx.GetTargetPtr()->GetDebugger(); 3461 CommandInterpreterRunOptions options; 3462 options.SetStopOnContinue(true); 3463 options.SetStopOnError(true); 3464 options.SetEchoCommands(false); 3465 options.SetPrintResults(true); 3466 options.SetPrintErrors(true); 3467 options.SetAddToHistory(false); 3468 3469 // Force Async: 3470 bool old_async = debugger.GetAsyncExecution(); 3471 debugger.SetAsyncExecution(true); 3472 debugger.GetCommandInterpreter().HandleCommands(GetCommands(), exc_ctx, 3473 options, result); 3474 debugger.SetAsyncExecution(old_async); 3475 lldb::ReturnStatus status = result.GetStatus(); 3476 if (status == eReturnStatusSuccessContinuingNoResult || 3477 status == eReturnStatusSuccessContinuingResult) 3478 return StopHookResult::AlreadyContinued; 3479 return StopHookResult::KeepStopped; 3480 } 3481 3482 // Target::StopHookScripted 3483 Status Target::StopHookScripted::SetScriptCallback( 3484 std::string class_name, StructuredData::ObjectSP extra_args_sp) { 3485 Status error; 3486 3487 ScriptInterpreter *script_interp = 3488 GetTarget()->GetDebugger().GetScriptInterpreter(); 3489 if (!script_interp) { 3490 error.SetErrorString("No script interpreter installed."); 3491 return error; 3492 } 3493 3494 m_class_name = class_name; 3495 m_extra_args.SetObjectSP(extra_args_sp); 3496 3497 m_implementation_sp = script_interp->CreateScriptedStopHook( 3498 GetTarget(), m_class_name.c_str(), m_extra_args, error); 3499 3500 return error; 3501 } 3502 3503 Target::StopHook::StopHookResult 3504 Target::StopHookScripted::HandleStop(ExecutionContext &exc_ctx, 3505 StreamSP output_sp) { 3506 assert(exc_ctx.GetTargetPtr() && "Can't call HandleStop on a context " 3507 "with no target"); 3508 3509 ScriptInterpreter *script_interp = 3510 GetTarget()->GetDebugger().GetScriptInterpreter(); 3511 if (!script_interp) 3512 return StopHookResult::KeepStopped; 3513 3514 bool should_stop = script_interp->ScriptedStopHookHandleStop( 3515 m_implementation_sp, exc_ctx, output_sp); 3516 3517 return should_stop ? StopHookResult::KeepStopped 3518 : StopHookResult::RequestContinue; 3519 } 3520 3521 void Target::StopHookScripted::GetSubclassDescription( 3522 Stream *s, lldb::DescriptionLevel level) const { 3523 if (level == eDescriptionLevelBrief) { 3524 s->PutCString(m_class_name); 3525 return; 3526 } 3527 s->Indent("Class:"); 3528 s->Printf("%s\n", m_class_name.c_str()); 3529 3530 // Now print the extra args: 3531 // FIXME: We should use StructuredData.GetDescription on the m_extra_args 3532 // but that seems to rely on some printing plugin that doesn't exist. 3533 if (!m_extra_args.IsValid()) 3534 return; 3535 StructuredData::ObjectSP object_sp = m_extra_args.GetObjectSP(); 3536 if (!object_sp || !object_sp->IsValid()) 3537 return; 3538 3539 StructuredData::Dictionary *as_dict = object_sp->GetAsDictionary(); 3540 if (!as_dict || !as_dict->IsValid()) 3541 return; 3542 3543 uint32_t num_keys = as_dict->GetSize(); 3544 if (num_keys == 0) 3545 return; 3546 3547 s->Indent("Args:\n"); 3548 s->SetIndentLevel(s->GetIndentLevel() + 4); 3549 3550 auto print_one_element = [&s](ConstString key, 3551 StructuredData::Object *object) { 3552 s->Indent(); 3553 s->Printf("%s : %s\n", key.GetCString(), 3554 object->GetStringValue().str().c_str()); 3555 return true; 3556 }; 3557 3558 as_dict->ForEach(print_one_element); 3559 3560 s->SetIndentLevel(s->GetIndentLevel() - 4); 3561 } 3562 3563 static constexpr OptionEnumValueElement g_dynamic_value_types[] = { 3564 { 3565 eNoDynamicValues, 3566 "no-dynamic-values", 3567 "Don't calculate the dynamic type of values", 3568 }, 3569 { 3570 eDynamicCanRunTarget, 3571 "run-target", 3572 "Calculate the dynamic type of values " 3573 "even if you have to run the target.", 3574 }, 3575 { 3576 eDynamicDontRunTarget, 3577 "no-run-target", 3578 "Calculate the dynamic type of values, but don't run the target.", 3579 }, 3580 }; 3581 3582 OptionEnumValues lldb_private::GetDynamicValueTypes() { 3583 return OptionEnumValues(g_dynamic_value_types); 3584 } 3585 3586 static constexpr OptionEnumValueElement g_inline_breakpoint_enums[] = { 3587 { 3588 eInlineBreakpointsNever, 3589 "never", 3590 "Never look for inline breakpoint locations (fastest). This setting " 3591 "should only be used if you know that no inlining occurs in your" 3592 "programs.", 3593 }, 3594 { 3595 eInlineBreakpointsHeaders, 3596 "headers", 3597 "Only check for inline breakpoint locations when setting breakpoints " 3598 "in header files, but not when setting breakpoint in implementation " 3599 "source files (default).", 3600 }, 3601 { 3602 eInlineBreakpointsAlways, 3603 "always", 3604 "Always look for inline breakpoint locations when setting file and " 3605 "line breakpoints (slower but most accurate).", 3606 }, 3607 }; 3608 3609 enum x86DisassemblyFlavor { 3610 eX86DisFlavorDefault, 3611 eX86DisFlavorIntel, 3612 eX86DisFlavorATT 3613 }; 3614 3615 static constexpr OptionEnumValueElement g_x86_dis_flavor_value_types[] = { 3616 { 3617 eX86DisFlavorDefault, 3618 "default", 3619 "Disassembler default (currently att).", 3620 }, 3621 { 3622 eX86DisFlavorIntel, 3623 "intel", 3624 "Intel disassembler flavor.", 3625 }, 3626 { 3627 eX86DisFlavorATT, 3628 "att", 3629 "AT&T disassembler flavor.", 3630 }, 3631 }; 3632 3633 static constexpr OptionEnumValueElement g_import_std_module_value_types[] = { 3634 { 3635 eImportStdModuleFalse, 3636 "false", 3637 "Never import the 'std' C++ module in the expression parser.", 3638 }, 3639 { 3640 eImportStdModuleFallback, 3641 "fallback", 3642 "Retry evaluating expressions with an imported 'std' C++ module if they" 3643 " failed to parse without the module. This allows evaluating more " 3644 "complex expressions involving C++ standard library types." 3645 }, 3646 { 3647 eImportStdModuleTrue, 3648 "true", 3649 "Always import the 'std' C++ module. This allows evaluating more " 3650 "complex expressions involving C++ standard library types. This feature" 3651 " is experimental." 3652 }, 3653 }; 3654 3655 static constexpr OptionEnumValueElement g_hex_immediate_style_values[] = { 3656 { 3657 Disassembler::eHexStyleC, 3658 "c", 3659 "C-style (0xffff).", 3660 }, 3661 { 3662 Disassembler::eHexStyleAsm, 3663 "asm", 3664 "Asm-style (0ffffh).", 3665 }, 3666 }; 3667 3668 static constexpr OptionEnumValueElement g_load_script_from_sym_file_values[] = { 3669 { 3670 eLoadScriptFromSymFileTrue, 3671 "true", 3672 "Load debug scripts inside symbol files", 3673 }, 3674 { 3675 eLoadScriptFromSymFileFalse, 3676 "false", 3677 "Do not load debug scripts inside symbol files.", 3678 }, 3679 { 3680 eLoadScriptFromSymFileWarn, 3681 "warn", 3682 "Warn about debug scripts inside symbol files but do not load them.", 3683 }, 3684 }; 3685 3686 static constexpr OptionEnumValueElement g_load_cwd_lldbinit_values[] = { 3687 { 3688 eLoadCWDlldbinitTrue, 3689 "true", 3690 "Load .lldbinit files from current directory", 3691 }, 3692 { 3693 eLoadCWDlldbinitFalse, 3694 "false", 3695 "Do not load .lldbinit files from current directory", 3696 }, 3697 { 3698 eLoadCWDlldbinitWarn, 3699 "warn", 3700 "Warn about loading .lldbinit files from current directory", 3701 }, 3702 }; 3703 3704 static constexpr OptionEnumValueElement g_memory_module_load_level_values[] = { 3705 { 3706 eMemoryModuleLoadLevelMinimal, 3707 "minimal", 3708 "Load minimal information when loading modules from memory. Currently " 3709 "this setting loads sections only.", 3710 }, 3711 { 3712 eMemoryModuleLoadLevelPartial, 3713 "partial", 3714 "Load partial information when loading modules from memory. Currently " 3715 "this setting loads sections and function bounds.", 3716 }, 3717 { 3718 eMemoryModuleLoadLevelComplete, 3719 "complete", 3720 "Load complete information when loading modules from memory. Currently " 3721 "this setting loads sections and all symbols.", 3722 }, 3723 }; 3724 3725 #define LLDB_PROPERTIES_target 3726 #include "TargetProperties.inc" 3727 3728 enum { 3729 #define LLDB_PROPERTIES_target 3730 #include "TargetPropertiesEnum.inc" 3731 ePropertyExperimental, 3732 }; 3733 3734 class TargetOptionValueProperties 3735 : public Cloneable<TargetOptionValueProperties, OptionValueProperties> { 3736 public: 3737 TargetOptionValueProperties(ConstString name) : Cloneable(name) {} 3738 3739 const Property *GetPropertyAtIndex(const ExecutionContext *exe_ctx, 3740 bool will_modify, 3741 uint32_t idx) const override { 3742 // When getting the value for a key from the target options, we will always 3743 // try and grab the setting from the current target if there is one. Else 3744 // we just use the one from this instance. 3745 if (exe_ctx) { 3746 Target *target = exe_ctx->GetTargetPtr(); 3747 if (target) { 3748 TargetOptionValueProperties *target_properties = 3749 static_cast<TargetOptionValueProperties *>( 3750 target->GetValueProperties().get()); 3751 if (this != target_properties) 3752 return target_properties->ProtectedGetPropertyAtIndex(idx); 3753 } 3754 } 3755 return ProtectedGetPropertyAtIndex(idx); 3756 } 3757 }; 3758 3759 // TargetProperties 3760 #define LLDB_PROPERTIES_target_experimental 3761 #include "TargetProperties.inc" 3762 3763 enum { 3764 #define LLDB_PROPERTIES_target_experimental 3765 #include "TargetPropertiesEnum.inc" 3766 }; 3767 3768 class TargetExperimentalOptionValueProperties 3769 : public Cloneable<TargetExperimentalOptionValueProperties, 3770 OptionValueProperties> { 3771 public: 3772 TargetExperimentalOptionValueProperties() 3773 : Cloneable(ConstString(Properties::GetExperimentalSettingsName())) {} 3774 }; 3775 3776 TargetExperimentalProperties::TargetExperimentalProperties() 3777 : Properties(OptionValuePropertiesSP( 3778 new TargetExperimentalOptionValueProperties())) { 3779 m_collection_sp->Initialize(g_target_experimental_properties); 3780 } 3781 3782 // TargetProperties 3783 TargetProperties::TargetProperties(Target *target) 3784 : Properties(), m_launch_info(), m_target(target) { 3785 if (target) { 3786 m_collection_sp = 3787 OptionValueProperties::CreateLocalCopy(Target::GetGlobalProperties()); 3788 3789 // Set callbacks to update launch_info whenever "settins set" updated any 3790 // of these properties 3791 m_collection_sp->SetValueChangedCallback( 3792 ePropertyArg0, [this] { Arg0ValueChangedCallback(); }); 3793 m_collection_sp->SetValueChangedCallback( 3794 ePropertyRunArgs, [this] { RunArgsValueChangedCallback(); }); 3795 m_collection_sp->SetValueChangedCallback( 3796 ePropertyEnvVars, [this] { EnvVarsValueChangedCallback(); }); 3797 m_collection_sp->SetValueChangedCallback( 3798 ePropertyUnsetEnvVars, [this] { EnvVarsValueChangedCallback(); }); 3799 m_collection_sp->SetValueChangedCallback( 3800 ePropertyInheritEnv, [this] { EnvVarsValueChangedCallback(); }); 3801 m_collection_sp->SetValueChangedCallback( 3802 ePropertyInputPath, [this] { InputPathValueChangedCallback(); }); 3803 m_collection_sp->SetValueChangedCallback( 3804 ePropertyOutputPath, [this] { OutputPathValueChangedCallback(); }); 3805 m_collection_sp->SetValueChangedCallback( 3806 ePropertyErrorPath, [this] { ErrorPathValueChangedCallback(); }); 3807 m_collection_sp->SetValueChangedCallback(ePropertyDetachOnError, [this] { 3808 DetachOnErrorValueChangedCallback(); 3809 }); 3810 m_collection_sp->SetValueChangedCallback( 3811 ePropertyDisableASLR, [this] { DisableASLRValueChangedCallback(); }); 3812 m_collection_sp->SetValueChangedCallback( 3813 ePropertyInheritTCC, [this] { InheritTCCValueChangedCallback(); }); 3814 m_collection_sp->SetValueChangedCallback( 3815 ePropertyDisableSTDIO, [this] { DisableSTDIOValueChangedCallback(); }); 3816 3817 m_collection_sp->SetValueChangedCallback( 3818 ePropertySaveObjectsDir, [this] { CheckJITObjectsDir(); }); 3819 m_experimental_properties_up = 3820 std::make_unique<TargetExperimentalProperties>(); 3821 m_collection_sp->AppendProperty( 3822 ConstString(Properties::GetExperimentalSettingsName()), 3823 ConstString("Experimental settings - setting these won't produce " 3824 "errors if the setting is not present."), 3825 true, m_experimental_properties_up->GetValueProperties()); 3826 } else { 3827 m_collection_sp = 3828 std::make_shared<TargetOptionValueProperties>(ConstString("target")); 3829 m_collection_sp->Initialize(g_target_properties); 3830 m_experimental_properties_up = 3831 std::make_unique<TargetExperimentalProperties>(); 3832 m_collection_sp->AppendProperty( 3833 ConstString(Properties::GetExperimentalSettingsName()), 3834 ConstString("Experimental settings - setting these won't produce " 3835 "errors if the setting is not present."), 3836 true, m_experimental_properties_up->GetValueProperties()); 3837 m_collection_sp->AppendProperty( 3838 ConstString("process"), ConstString("Settings specific to processes."), 3839 true, Process::GetGlobalProperties().GetValueProperties()); 3840 m_collection_sp->SetValueChangedCallback( 3841 ePropertySaveObjectsDir, [this] { CheckJITObjectsDir(); }); 3842 } 3843 } 3844 3845 TargetProperties::~TargetProperties() = default; 3846 3847 void TargetProperties::UpdateLaunchInfoFromProperties() { 3848 Arg0ValueChangedCallback(); 3849 RunArgsValueChangedCallback(); 3850 EnvVarsValueChangedCallback(); 3851 InputPathValueChangedCallback(); 3852 OutputPathValueChangedCallback(); 3853 ErrorPathValueChangedCallback(); 3854 DetachOnErrorValueChangedCallback(); 3855 DisableASLRValueChangedCallback(); 3856 InheritTCCValueChangedCallback(); 3857 DisableSTDIOValueChangedCallback(); 3858 } 3859 3860 bool TargetProperties::GetInjectLocalVariables( 3861 ExecutionContext *exe_ctx) const { 3862 const Property *exp_property = m_collection_sp->GetPropertyAtIndex( 3863 exe_ctx, false, ePropertyExperimental); 3864 OptionValueProperties *exp_values = 3865 exp_property->GetValue()->GetAsProperties(); 3866 if (exp_values) 3867 return exp_values->GetPropertyAtIndexAsBoolean( 3868 exe_ctx, ePropertyInjectLocalVars, true); 3869 else 3870 return true; 3871 } 3872 3873 void TargetProperties::SetInjectLocalVariables(ExecutionContext *exe_ctx, 3874 bool b) { 3875 const Property *exp_property = 3876 m_collection_sp->GetPropertyAtIndex(exe_ctx, true, ePropertyExperimental); 3877 OptionValueProperties *exp_values = 3878 exp_property->GetValue()->GetAsProperties(); 3879 if (exp_values) 3880 exp_values->SetPropertyAtIndexAsBoolean(exe_ctx, ePropertyInjectLocalVars, 3881 true); 3882 } 3883 3884 ArchSpec TargetProperties::GetDefaultArchitecture() const { 3885 OptionValueArch *value = m_collection_sp->GetPropertyAtIndexAsOptionValueArch( 3886 nullptr, ePropertyDefaultArch); 3887 if (value) 3888 return value->GetCurrentValue(); 3889 return ArchSpec(); 3890 } 3891 3892 void TargetProperties::SetDefaultArchitecture(const ArchSpec &arch) { 3893 OptionValueArch *value = m_collection_sp->GetPropertyAtIndexAsOptionValueArch( 3894 nullptr, ePropertyDefaultArch); 3895 if (value) 3896 return value->SetCurrentValue(arch, true); 3897 } 3898 3899 bool TargetProperties::GetMoveToNearestCode() const { 3900 const uint32_t idx = ePropertyMoveToNearestCode; 3901 return m_collection_sp->GetPropertyAtIndexAsBoolean( 3902 nullptr, idx, g_target_properties[idx].default_uint_value != 0); 3903 } 3904 3905 lldb::DynamicValueType TargetProperties::GetPreferDynamicValue() const { 3906 const uint32_t idx = ePropertyPreferDynamic; 3907 return (lldb::DynamicValueType) 3908 m_collection_sp->GetPropertyAtIndexAsEnumeration( 3909 nullptr, idx, g_target_properties[idx].default_uint_value); 3910 } 3911 3912 bool TargetProperties::SetPreferDynamicValue(lldb::DynamicValueType d) { 3913 const uint32_t idx = ePropertyPreferDynamic; 3914 return m_collection_sp->SetPropertyAtIndexAsEnumeration(nullptr, idx, d); 3915 } 3916 3917 bool TargetProperties::GetPreloadSymbols() const { 3918 const uint32_t idx = ePropertyPreloadSymbols; 3919 return m_collection_sp->GetPropertyAtIndexAsBoolean( 3920 nullptr, idx, g_target_properties[idx].default_uint_value != 0); 3921 } 3922 3923 void TargetProperties::SetPreloadSymbols(bool b) { 3924 const uint32_t idx = ePropertyPreloadSymbols; 3925 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b); 3926 } 3927 3928 bool TargetProperties::GetDisableASLR() const { 3929 const uint32_t idx = ePropertyDisableASLR; 3930 return m_collection_sp->GetPropertyAtIndexAsBoolean( 3931 nullptr, idx, g_target_properties[idx].default_uint_value != 0); 3932 } 3933 3934 void TargetProperties::SetDisableASLR(bool b) { 3935 const uint32_t idx = ePropertyDisableASLR; 3936 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b); 3937 } 3938 3939 bool TargetProperties::GetInheritTCC() const { 3940 const uint32_t idx = ePropertyInheritTCC; 3941 return m_collection_sp->GetPropertyAtIndexAsBoolean( 3942 nullptr, idx, g_target_properties[idx].default_uint_value != 0); 3943 } 3944 3945 void TargetProperties::SetInheritTCC(bool b) { 3946 const uint32_t idx = ePropertyInheritTCC; 3947 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b); 3948 } 3949 3950 bool TargetProperties::GetDetachOnError() const { 3951 const uint32_t idx = ePropertyDetachOnError; 3952 return m_collection_sp->GetPropertyAtIndexAsBoolean( 3953 nullptr, idx, g_target_properties[idx].default_uint_value != 0); 3954 } 3955 3956 void TargetProperties::SetDetachOnError(bool b) { 3957 const uint32_t idx = ePropertyDetachOnError; 3958 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b); 3959 } 3960 3961 bool TargetProperties::GetDisableSTDIO() const { 3962 const uint32_t idx = ePropertyDisableSTDIO; 3963 return m_collection_sp->GetPropertyAtIndexAsBoolean( 3964 nullptr, idx, g_target_properties[idx].default_uint_value != 0); 3965 } 3966 3967 void TargetProperties::SetDisableSTDIO(bool b) { 3968 const uint32_t idx = ePropertyDisableSTDIO; 3969 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b); 3970 } 3971 3972 const char *TargetProperties::GetDisassemblyFlavor() const { 3973 const uint32_t idx = ePropertyDisassemblyFlavor; 3974 const char *return_value; 3975 3976 x86DisassemblyFlavor flavor_value = 3977 (x86DisassemblyFlavor)m_collection_sp->GetPropertyAtIndexAsEnumeration( 3978 nullptr, idx, g_target_properties[idx].default_uint_value); 3979 return_value = g_x86_dis_flavor_value_types[flavor_value].string_value; 3980 return return_value; 3981 } 3982 3983 InlineStrategy TargetProperties::GetInlineStrategy() const { 3984 const uint32_t idx = ePropertyInlineStrategy; 3985 return (InlineStrategy)m_collection_sp->GetPropertyAtIndexAsEnumeration( 3986 nullptr, idx, g_target_properties[idx].default_uint_value); 3987 } 3988 3989 llvm::StringRef TargetProperties::GetArg0() const { 3990 const uint32_t idx = ePropertyArg0; 3991 return m_collection_sp->GetPropertyAtIndexAsString(nullptr, idx, 3992 llvm::StringRef()); 3993 } 3994 3995 void TargetProperties::SetArg0(llvm::StringRef arg) { 3996 const uint32_t idx = ePropertyArg0; 3997 m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, arg); 3998 m_launch_info.SetArg0(arg); 3999 } 4000 4001 bool TargetProperties::GetRunArguments(Args &args) const { 4002 const uint32_t idx = ePropertyRunArgs; 4003 return m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, args); 4004 } 4005 4006 void TargetProperties::SetRunArguments(const Args &args) { 4007 const uint32_t idx = ePropertyRunArgs; 4008 m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, args); 4009 m_launch_info.GetArguments() = args; 4010 } 4011 4012 Environment TargetProperties::ComputeEnvironment() const { 4013 Environment env; 4014 4015 if (m_target && 4016 m_collection_sp->GetPropertyAtIndexAsBoolean( 4017 nullptr, ePropertyInheritEnv, 4018 g_target_properties[ePropertyInheritEnv].default_uint_value != 0)) { 4019 if (auto platform_sp = m_target->GetPlatform()) { 4020 Environment platform_env = platform_sp->GetEnvironment(); 4021 for (const auto &KV : platform_env) 4022 env[KV.first()] = KV.second; 4023 } 4024 } 4025 4026 Args property_unset_env; 4027 m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, ePropertyUnsetEnvVars, 4028 property_unset_env); 4029 for (const auto &var : property_unset_env) 4030 env.erase(var.ref()); 4031 4032 Args property_env; 4033 m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, ePropertyEnvVars, 4034 property_env); 4035 for (const auto &KV : Environment(property_env)) 4036 env[KV.first()] = KV.second; 4037 4038 return env; 4039 } 4040 4041 Environment TargetProperties::GetEnvironment() const { 4042 return ComputeEnvironment(); 4043 } 4044 4045 Environment TargetProperties::GetInheritedEnvironment() const { 4046 Environment environment; 4047 4048 if (m_target == nullptr) 4049 return environment; 4050 4051 if (!m_collection_sp->GetPropertyAtIndexAsBoolean( 4052 nullptr, ePropertyInheritEnv, 4053 g_target_properties[ePropertyInheritEnv].default_uint_value != 0)) 4054 return environment; 4055 4056 PlatformSP platform_sp = m_target->GetPlatform(); 4057 if (platform_sp == nullptr) 4058 return environment; 4059 4060 Environment platform_environment = platform_sp->GetEnvironment(); 4061 for (const auto &KV : platform_environment) 4062 environment[KV.first()] = KV.second; 4063 4064 Args property_unset_environment; 4065 m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, ePropertyUnsetEnvVars, 4066 property_unset_environment); 4067 for (const auto &var : property_unset_environment) 4068 environment.erase(var.ref()); 4069 4070 return environment; 4071 } 4072 4073 Environment TargetProperties::GetTargetEnvironment() const { 4074 Args property_environment; 4075 m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, ePropertyEnvVars, 4076 property_environment); 4077 Environment environment; 4078 for (const auto &KV : Environment(property_environment)) 4079 environment[KV.first()] = KV.second; 4080 4081 return environment; 4082 } 4083 4084 void TargetProperties::SetEnvironment(Environment env) { 4085 // TODO: Get rid of the Args intermediate step 4086 const uint32_t idx = ePropertyEnvVars; 4087 m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, Args(env)); 4088 } 4089 4090 bool TargetProperties::GetSkipPrologue() const { 4091 const uint32_t idx = ePropertySkipPrologue; 4092 return m_collection_sp->GetPropertyAtIndexAsBoolean( 4093 nullptr, idx, g_target_properties[idx].default_uint_value != 0); 4094 } 4095 4096 PathMappingList &TargetProperties::GetSourcePathMap() const { 4097 const uint32_t idx = ePropertySourceMap; 4098 OptionValuePathMappings *option_value = 4099 m_collection_sp->GetPropertyAtIndexAsOptionValuePathMappings(nullptr, 4100 false, idx); 4101 assert(option_value); 4102 return option_value->GetCurrentValue(); 4103 } 4104 4105 void TargetProperties::AppendExecutableSearchPaths(const FileSpec &dir) { 4106 const uint32_t idx = ePropertyExecutableSearchPaths; 4107 OptionValueFileSpecList *option_value = 4108 m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr, 4109 false, idx); 4110 assert(option_value); 4111 option_value->AppendCurrentValue(dir); 4112 } 4113 4114 FileSpecList TargetProperties::GetExecutableSearchPaths() { 4115 const uint32_t idx = ePropertyExecutableSearchPaths; 4116 const OptionValueFileSpecList *option_value = 4117 m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr, 4118 false, idx); 4119 assert(option_value); 4120 return option_value->GetCurrentValue(); 4121 } 4122 4123 FileSpecList TargetProperties::GetDebugFileSearchPaths() { 4124 const uint32_t idx = ePropertyDebugFileSearchPaths; 4125 const OptionValueFileSpecList *option_value = 4126 m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr, 4127 false, idx); 4128 assert(option_value); 4129 return option_value->GetCurrentValue(); 4130 } 4131 4132 FileSpecList TargetProperties::GetClangModuleSearchPaths() { 4133 const uint32_t idx = ePropertyClangModuleSearchPaths; 4134 const OptionValueFileSpecList *option_value = 4135 m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr, 4136 false, idx); 4137 assert(option_value); 4138 return option_value->GetCurrentValue(); 4139 } 4140 4141 bool TargetProperties::GetEnableAutoImportClangModules() const { 4142 const uint32_t idx = ePropertyAutoImportClangModules; 4143 return m_collection_sp->GetPropertyAtIndexAsBoolean( 4144 nullptr, idx, g_target_properties[idx].default_uint_value != 0); 4145 } 4146 4147 ImportStdModule TargetProperties::GetImportStdModule() const { 4148 const uint32_t idx = ePropertyImportStdModule; 4149 return (ImportStdModule)m_collection_sp->GetPropertyAtIndexAsEnumeration( 4150 nullptr, idx, g_target_properties[idx].default_uint_value); 4151 } 4152 4153 bool TargetProperties::GetEnableAutoApplyFixIts() const { 4154 const uint32_t idx = ePropertyAutoApplyFixIts; 4155 return m_collection_sp->GetPropertyAtIndexAsBoolean( 4156 nullptr, idx, g_target_properties[idx].default_uint_value != 0); 4157 } 4158 4159 uint64_t TargetProperties::GetNumberOfRetriesWithFixits() const { 4160 const uint32_t idx = ePropertyRetriesWithFixIts; 4161 return m_collection_sp->GetPropertyAtIndexAsUInt64( 4162 nullptr, idx, g_target_properties[idx].default_uint_value); 4163 } 4164 4165 bool TargetProperties::GetEnableNotifyAboutFixIts() const { 4166 const uint32_t idx = ePropertyNotifyAboutFixIts; 4167 return m_collection_sp->GetPropertyAtIndexAsBoolean( 4168 nullptr, idx, g_target_properties[idx].default_uint_value != 0); 4169 } 4170 4171 FileSpec TargetProperties::GetSaveJITObjectsDir() const { 4172 const uint32_t idx = ePropertySaveObjectsDir; 4173 return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx); 4174 } 4175 4176 void TargetProperties::CheckJITObjectsDir() { 4177 const uint32_t idx = ePropertySaveObjectsDir; 4178 FileSpec new_dir = GetSaveJITObjectsDir(); 4179 const FileSystem &instance = FileSystem::Instance(); 4180 bool exists = instance.Exists(new_dir); 4181 bool is_directory = instance.IsDirectory(new_dir); 4182 std::string path = new_dir.GetPath(true); 4183 bool writable = llvm::sys::fs::can_write(path); 4184 if (exists && is_directory && writable) 4185 return; 4186 m_collection_sp->GetPropertyAtIndex(nullptr, true, idx)->GetValue() 4187 ->Clear(); 4188 StreamSP error_strm_sp; 4189 if (m_target) { 4190 // FIXME: How can I warn the user when setting this on the Debugger? 4191 error_strm_sp = m_target->GetDebugger().GetAsyncErrorStream(); 4192 } else if (Debugger::GetNumDebuggers() == 1) { 4193 error_strm_sp = Debugger::GetDebuggerAtIndex(0)->GetAsyncErrorStream(); 4194 } 4195 if (error_strm_sp) { 4196 error_strm_sp->Format("JIT object dir '{0}' ", path); 4197 if (!exists) 4198 error_strm_sp->PutCString("does not exist."); 4199 else if (!is_directory) 4200 error_strm_sp->PutCString("is not a directory."); 4201 else if (!writable) 4202 error_strm_sp->PutCString("is not writable."); 4203 error_strm_sp->EOL(); 4204 error_strm_sp->Flush(); 4205 } 4206 } 4207 4208 bool TargetProperties::GetEnableSyntheticValue() const { 4209 const uint32_t idx = ePropertyEnableSynthetic; 4210 return m_collection_sp->GetPropertyAtIndexAsBoolean( 4211 nullptr, idx, g_target_properties[idx].default_uint_value != 0); 4212 } 4213 4214 uint32_t TargetProperties::GetMaxZeroPaddingInFloatFormat() const { 4215 const uint32_t idx = ePropertyMaxZeroPaddingInFloatFormat; 4216 return m_collection_sp->GetPropertyAtIndexAsUInt64( 4217 nullptr, idx, g_target_properties[idx].default_uint_value); 4218 } 4219 4220 uint32_t TargetProperties::GetMaximumNumberOfChildrenToDisplay() const { 4221 const uint32_t idx = ePropertyMaxChildrenCount; 4222 return m_collection_sp->GetPropertyAtIndexAsSInt64( 4223 nullptr, idx, g_target_properties[idx].default_uint_value); 4224 } 4225 4226 uint32_t TargetProperties::GetMaximumSizeOfStringSummary() const { 4227 const uint32_t idx = ePropertyMaxSummaryLength; 4228 return m_collection_sp->GetPropertyAtIndexAsSInt64( 4229 nullptr, idx, g_target_properties[idx].default_uint_value); 4230 } 4231 4232 uint32_t TargetProperties::GetMaximumMemReadSize() const { 4233 const uint32_t idx = ePropertyMaxMemReadSize; 4234 return m_collection_sp->GetPropertyAtIndexAsSInt64( 4235 nullptr, idx, g_target_properties[idx].default_uint_value); 4236 } 4237 4238 FileSpec TargetProperties::GetStandardInputPath() const { 4239 const uint32_t idx = ePropertyInputPath; 4240 return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx); 4241 } 4242 4243 void TargetProperties::SetStandardInputPath(llvm::StringRef path) { 4244 const uint32_t idx = ePropertyInputPath; 4245 m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, path); 4246 } 4247 4248 FileSpec TargetProperties::GetStandardOutputPath() const { 4249 const uint32_t idx = ePropertyOutputPath; 4250 return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx); 4251 } 4252 4253 void TargetProperties::SetStandardOutputPath(llvm::StringRef path) { 4254 const uint32_t idx = ePropertyOutputPath; 4255 m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, path); 4256 } 4257 4258 FileSpec TargetProperties::GetStandardErrorPath() const { 4259 const uint32_t idx = ePropertyErrorPath; 4260 return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx); 4261 } 4262 4263 void TargetProperties::SetStandardErrorPath(llvm::StringRef path) { 4264 const uint32_t idx = ePropertyErrorPath; 4265 m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, path); 4266 } 4267 4268 LanguageType TargetProperties::GetLanguage() const { 4269 OptionValueLanguage *value = 4270 m_collection_sp->GetPropertyAtIndexAsOptionValueLanguage( 4271 nullptr, ePropertyLanguage); 4272 if (value) 4273 return value->GetCurrentValue(); 4274 return LanguageType(); 4275 } 4276 4277 llvm::StringRef TargetProperties::GetExpressionPrefixContents() { 4278 const uint32_t idx = ePropertyExprPrefix; 4279 OptionValueFileSpec *file = 4280 m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpec(nullptr, false, 4281 idx); 4282 if (file) { 4283 DataBufferSP data_sp(file->GetFileContents()); 4284 if (data_sp) 4285 return llvm::StringRef( 4286 reinterpret_cast<const char *>(data_sp->GetBytes()), 4287 data_sp->GetByteSize()); 4288 } 4289 return ""; 4290 } 4291 4292 uint64_t TargetProperties::GetExprErrorLimit() const { 4293 const uint32_t idx = ePropertyExprErrorLimit; 4294 return m_collection_sp->GetPropertyAtIndexAsUInt64( 4295 nullptr, idx, g_target_properties[idx].default_uint_value); 4296 } 4297 4298 bool TargetProperties::GetBreakpointsConsultPlatformAvoidList() { 4299 const uint32_t idx = ePropertyBreakpointUseAvoidList; 4300 return m_collection_sp->GetPropertyAtIndexAsBoolean( 4301 nullptr, idx, g_target_properties[idx].default_uint_value != 0); 4302 } 4303 4304 bool TargetProperties::GetUseHexImmediates() const { 4305 const uint32_t idx = ePropertyUseHexImmediates; 4306 return m_collection_sp->GetPropertyAtIndexAsBoolean( 4307 nullptr, idx, g_target_properties[idx].default_uint_value != 0); 4308 } 4309 4310 bool TargetProperties::GetUseFastStepping() const { 4311 const uint32_t idx = ePropertyUseFastStepping; 4312 return m_collection_sp->GetPropertyAtIndexAsBoolean( 4313 nullptr, idx, g_target_properties[idx].default_uint_value != 0); 4314 } 4315 4316 bool TargetProperties::GetDisplayExpressionsInCrashlogs() const { 4317 const uint32_t idx = ePropertyDisplayExpressionsInCrashlogs; 4318 return m_collection_sp->GetPropertyAtIndexAsBoolean( 4319 nullptr, idx, g_target_properties[idx].default_uint_value != 0); 4320 } 4321 4322 LoadScriptFromSymFile TargetProperties::GetLoadScriptFromSymbolFile() const { 4323 const uint32_t idx = ePropertyLoadScriptFromSymbolFile; 4324 return (LoadScriptFromSymFile) 4325 m_collection_sp->GetPropertyAtIndexAsEnumeration( 4326 nullptr, idx, g_target_properties[idx].default_uint_value); 4327 } 4328 4329 LoadCWDlldbinitFile TargetProperties::GetLoadCWDlldbinitFile() const { 4330 const uint32_t idx = ePropertyLoadCWDlldbinitFile; 4331 return (LoadCWDlldbinitFile)m_collection_sp->GetPropertyAtIndexAsEnumeration( 4332 nullptr, idx, g_target_properties[idx].default_uint_value); 4333 } 4334 4335 Disassembler::HexImmediateStyle TargetProperties::GetHexImmediateStyle() const { 4336 const uint32_t idx = ePropertyHexImmediateStyle; 4337 return (Disassembler::HexImmediateStyle) 4338 m_collection_sp->GetPropertyAtIndexAsEnumeration( 4339 nullptr, idx, g_target_properties[idx].default_uint_value); 4340 } 4341 4342 MemoryModuleLoadLevel TargetProperties::GetMemoryModuleLoadLevel() const { 4343 const uint32_t idx = ePropertyMemoryModuleLoadLevel; 4344 return (MemoryModuleLoadLevel) 4345 m_collection_sp->GetPropertyAtIndexAsEnumeration( 4346 nullptr, idx, g_target_properties[idx].default_uint_value); 4347 } 4348 4349 bool TargetProperties::GetUserSpecifiedTrapHandlerNames(Args &args) const { 4350 const uint32_t idx = ePropertyTrapHandlerNames; 4351 return m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, args); 4352 } 4353 4354 void TargetProperties::SetUserSpecifiedTrapHandlerNames(const Args &args) { 4355 const uint32_t idx = ePropertyTrapHandlerNames; 4356 m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, args); 4357 } 4358 4359 bool TargetProperties::GetDisplayRuntimeSupportValues() const { 4360 const uint32_t idx = ePropertyDisplayRuntimeSupportValues; 4361 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, false); 4362 } 4363 4364 void TargetProperties::SetDisplayRuntimeSupportValues(bool b) { 4365 const uint32_t idx = ePropertyDisplayRuntimeSupportValues; 4366 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b); 4367 } 4368 4369 bool TargetProperties::GetDisplayRecognizedArguments() const { 4370 const uint32_t idx = ePropertyDisplayRecognizedArguments; 4371 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, false); 4372 } 4373 4374 void TargetProperties::SetDisplayRecognizedArguments(bool b) { 4375 const uint32_t idx = ePropertyDisplayRecognizedArguments; 4376 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b); 4377 } 4378 4379 const ProcessLaunchInfo &TargetProperties::GetProcessLaunchInfo() const { 4380 return m_launch_info; 4381 } 4382 4383 void TargetProperties::SetProcessLaunchInfo( 4384 const ProcessLaunchInfo &launch_info) { 4385 m_launch_info = launch_info; 4386 SetArg0(launch_info.GetArg0()); 4387 SetRunArguments(launch_info.GetArguments()); 4388 SetEnvironment(launch_info.GetEnvironment()); 4389 const FileAction *input_file_action = 4390 launch_info.GetFileActionForFD(STDIN_FILENO); 4391 if (input_file_action) { 4392 SetStandardInputPath(input_file_action->GetPath()); 4393 } 4394 const FileAction *output_file_action = 4395 launch_info.GetFileActionForFD(STDOUT_FILENO); 4396 if (output_file_action) { 4397 SetStandardOutputPath(output_file_action->GetPath()); 4398 } 4399 const FileAction *error_file_action = 4400 launch_info.GetFileActionForFD(STDERR_FILENO); 4401 if (error_file_action) { 4402 SetStandardErrorPath(error_file_action->GetPath()); 4403 } 4404 SetDetachOnError(launch_info.GetFlags().Test(lldb::eLaunchFlagDetachOnError)); 4405 SetDisableASLR(launch_info.GetFlags().Test(lldb::eLaunchFlagDisableASLR)); 4406 SetInheritTCC( 4407 launch_info.GetFlags().Test(lldb::eLaunchFlagInheritTCCFromParent)); 4408 SetDisableSTDIO(launch_info.GetFlags().Test(lldb::eLaunchFlagDisableSTDIO)); 4409 } 4410 4411 bool TargetProperties::GetRequireHardwareBreakpoints() const { 4412 const uint32_t idx = ePropertyRequireHardwareBreakpoints; 4413 return m_collection_sp->GetPropertyAtIndexAsBoolean( 4414 nullptr, idx, g_target_properties[idx].default_uint_value != 0); 4415 } 4416 4417 void TargetProperties::SetRequireHardwareBreakpoints(bool b) { 4418 const uint32_t idx = ePropertyRequireHardwareBreakpoints; 4419 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b); 4420 } 4421 4422 bool TargetProperties::GetAutoInstallMainExecutable() const { 4423 const uint32_t idx = ePropertyAutoInstallMainExecutable; 4424 return m_collection_sp->GetPropertyAtIndexAsBoolean( 4425 nullptr, idx, g_target_properties[idx].default_uint_value != 0); 4426 } 4427 4428 void TargetProperties::Arg0ValueChangedCallback() { 4429 m_launch_info.SetArg0(GetArg0()); 4430 } 4431 4432 void TargetProperties::RunArgsValueChangedCallback() { 4433 Args args; 4434 if (GetRunArguments(args)) 4435 m_launch_info.GetArguments() = args; 4436 } 4437 4438 void TargetProperties::EnvVarsValueChangedCallback() { 4439 m_launch_info.GetEnvironment() = ComputeEnvironment(); 4440 } 4441 4442 void TargetProperties::InputPathValueChangedCallback() { 4443 m_launch_info.AppendOpenFileAction(STDIN_FILENO, GetStandardInputPath(), true, 4444 false); 4445 } 4446 4447 void TargetProperties::OutputPathValueChangedCallback() { 4448 m_launch_info.AppendOpenFileAction(STDOUT_FILENO, GetStandardOutputPath(), 4449 false, true); 4450 } 4451 4452 void TargetProperties::ErrorPathValueChangedCallback() { 4453 m_launch_info.AppendOpenFileAction(STDERR_FILENO, GetStandardErrorPath(), 4454 false, true); 4455 } 4456 4457 void TargetProperties::DetachOnErrorValueChangedCallback() { 4458 if (GetDetachOnError()) 4459 m_launch_info.GetFlags().Set(lldb::eLaunchFlagDetachOnError); 4460 else 4461 m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDetachOnError); 4462 } 4463 4464 void TargetProperties::DisableASLRValueChangedCallback() { 4465 if (GetDisableASLR()) 4466 m_launch_info.GetFlags().Set(lldb::eLaunchFlagDisableASLR); 4467 else 4468 m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDisableASLR); 4469 } 4470 4471 void TargetProperties::InheritTCCValueChangedCallback() { 4472 if (GetInheritTCC()) 4473 m_launch_info.GetFlags().Set(lldb::eLaunchFlagInheritTCCFromParent); 4474 else 4475 m_launch_info.GetFlags().Clear(lldb::eLaunchFlagInheritTCCFromParent); 4476 } 4477 4478 void TargetProperties::DisableSTDIOValueChangedCallback() { 4479 if (GetDisableSTDIO()) 4480 m_launch_info.GetFlags().Set(lldb::eLaunchFlagDisableSTDIO); 4481 else 4482 m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDisableSTDIO); 4483 } 4484 4485 bool TargetProperties::GetDebugUtilityExpression() const { 4486 const uint32_t idx = ePropertyDebugUtilityExpression; 4487 return m_collection_sp->GetPropertyAtIndexAsBoolean( 4488 nullptr, idx, g_target_properties[idx].default_uint_value != 0); 4489 } 4490 4491 void TargetProperties::SetDebugUtilityExpression(bool debug) { 4492 const uint32_t idx = ePropertyDebugUtilityExpression; 4493 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, debug); 4494 } 4495 4496 // Target::TargetEventData 4497 4498 Target::TargetEventData::TargetEventData(const lldb::TargetSP &target_sp) 4499 : EventData(), m_target_sp(target_sp), m_module_list() {} 4500 4501 Target::TargetEventData::TargetEventData(const lldb::TargetSP &target_sp, 4502 const ModuleList &module_list) 4503 : EventData(), m_target_sp(target_sp), m_module_list(module_list) {} 4504 4505 Target::TargetEventData::~TargetEventData() = default; 4506 4507 ConstString Target::TargetEventData::GetFlavorString() { 4508 static ConstString g_flavor("Target::TargetEventData"); 4509 return g_flavor; 4510 } 4511 4512 void Target::TargetEventData::Dump(Stream *s) const { 4513 for (size_t i = 0; i < m_module_list.GetSize(); ++i) { 4514 if (i != 0) 4515 *s << ", "; 4516 m_module_list.GetModuleAtIndex(i)->GetDescription( 4517 s->AsRawOstream(), lldb::eDescriptionLevelBrief); 4518 } 4519 } 4520 4521 const Target::TargetEventData * 4522 Target::TargetEventData::GetEventDataFromEvent(const Event *event_ptr) { 4523 if (event_ptr) { 4524 const EventData *event_data = event_ptr->GetData(); 4525 if (event_data && 4526 event_data->GetFlavor() == TargetEventData::GetFlavorString()) 4527 return static_cast<const TargetEventData *>(event_ptr->GetData()); 4528 } 4529 return nullptr; 4530 } 4531 4532 TargetSP Target::TargetEventData::GetTargetFromEvent(const Event *event_ptr) { 4533 TargetSP target_sp; 4534 const TargetEventData *event_data = GetEventDataFromEvent(event_ptr); 4535 if (event_data) 4536 target_sp = event_data->m_target_sp; 4537 return target_sp; 4538 } 4539 4540 ModuleList 4541 Target::TargetEventData::GetModuleListFromEvent(const Event *event_ptr) { 4542 ModuleList module_list; 4543 const TargetEventData *event_data = GetEventDataFromEvent(event_ptr); 4544 if (event_data) 4545 module_list = event_data->m_module_list; 4546 return module_list; 4547 } 4548 4549 std::recursive_mutex &Target::GetAPIMutex() { 4550 if (GetProcessSP() && GetProcessSP()->CurrentThreadIsPrivateStateThread()) 4551 return m_private_mutex; 4552 else 4553 return m_mutex; 4554 } 4555 4556 /// Get metrics associated with this target in JSON format. 4557 llvm::json::Value Target::ReportStatistics() { return m_stats.ToJSON(*this); } 4558