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