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