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