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