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