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