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