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