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 #include "lldb/Target/Target.h" 11 12 // C Includes 13 // C++ Includes 14 // Other libraries and framework includes 15 // Project includes 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/StreamString.h" 29 #include "lldb/Core/Timer.h" 30 #include "lldb/Core/ValueObject.h" 31 #include "lldb/Expression/ClangASTSource.h" 32 #include "lldb/Expression/ClangUserExpression.h" 33 #include "lldb/Host/Host.h" 34 #include "lldb/Interpreter/CommandInterpreter.h" 35 #include "lldb/Interpreter/CommandReturnObject.h" 36 #include "lldb/Interpreter/OptionGroupWatchpoint.h" 37 #include "lldb/Interpreter/OptionValues.h" 38 #include "lldb/Interpreter/Property.h" 39 #include "lldb/lldb-private-log.h" 40 #include "lldb/Symbol/ObjectFile.h" 41 #include "lldb/Target/Process.h" 42 #include "lldb/Target/StackFrame.h" 43 #include "lldb/Target/Thread.h" 44 #include "lldb/Target/ThreadSpec.h" 45 46 using namespace lldb; 47 using namespace lldb_private; 48 49 ConstString & 50 Target::GetStaticBroadcasterClass () 51 { 52 static ConstString class_name ("lldb.target"); 53 return class_name; 54 } 55 56 //---------------------------------------------------------------------- 57 // Target constructor 58 //---------------------------------------------------------------------- 59 Target::Target(Debugger &debugger, const ArchSpec &target_arch, const lldb::PlatformSP &platform_sp) : 60 TargetProperties (this), 61 Broadcaster (&debugger, "lldb.target"), 62 ExecutionContextScope (), 63 m_debugger (debugger), 64 m_platform_sp (platform_sp), 65 m_mutex (Mutex::eMutexTypeRecursive), 66 m_arch (target_arch), 67 m_images (), 68 m_section_load_list (), 69 m_breakpoint_list (false), 70 m_internal_breakpoint_list (true), 71 m_watchpoint_list (), 72 m_process_sp (), 73 m_valid (true), 74 m_search_filter_sp (), 75 m_image_search_paths (ImageSearchPathsChanged, this), 76 m_scratch_ast_context_ap (NULL), 77 m_scratch_ast_source_ap (NULL), 78 m_ast_importer_ap (NULL), 79 m_persistent_variables (), 80 m_source_manager(*this), 81 m_stop_hooks (), 82 m_stop_hook_next_id (0), 83 m_suppress_stop_hooks (false), 84 m_suppress_synthetic_value(false) 85 { 86 SetEventName (eBroadcastBitBreakpointChanged, "breakpoint-changed"); 87 SetEventName (eBroadcastBitModulesLoaded, "modules-loaded"); 88 SetEventName (eBroadcastBitModulesUnloaded, "modules-unloaded"); 89 90 CheckInWithManager(); 91 92 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT)); 93 if (log) 94 log->Printf ("%p Target::Target()", this); 95 } 96 97 //---------------------------------------------------------------------- 98 // Destructor 99 //---------------------------------------------------------------------- 100 Target::~Target() 101 { 102 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT)); 103 if (log) 104 log->Printf ("%p Target::~Target()", this); 105 DeleteCurrentProcess (); 106 } 107 108 void 109 Target::Dump (Stream *s, lldb::DescriptionLevel description_level) 110 { 111 // s->Printf("%.*p: ", (int)sizeof(void*) * 2, this); 112 if (description_level != lldb::eDescriptionLevelBrief) 113 { 114 s->Indent(); 115 s->PutCString("Target\n"); 116 s->IndentMore(); 117 m_images.Dump(s); 118 m_breakpoint_list.Dump(s); 119 m_internal_breakpoint_list.Dump(s); 120 s->IndentLess(); 121 } 122 else 123 { 124 Module *exe_module = GetExecutableModulePointer(); 125 if (exe_module) 126 s->PutCString (exe_module->GetFileSpec().GetFilename().GetCString()); 127 else 128 s->PutCString ("No executable module."); 129 } 130 } 131 132 void 133 Target::DeleteCurrentProcess () 134 { 135 if (m_process_sp.get()) 136 { 137 m_section_load_list.Clear(); 138 if (m_process_sp->IsAlive()) 139 m_process_sp->Destroy(); 140 141 m_process_sp->Finalize(); 142 143 // Do any cleanup of the target we need to do between process instances. 144 // NB It is better to do this before destroying the process in case the 145 // clean up needs some help from the process. 146 m_breakpoint_list.ClearAllBreakpointSites(); 147 m_internal_breakpoint_list.ClearAllBreakpointSites(); 148 // Disable watchpoints just on the debugger side. 149 Mutex::Locker locker; 150 this->GetWatchpointList().GetListMutex(locker); 151 DisableAllWatchpoints(false); 152 ClearAllWatchpointHitCounts(); 153 m_process_sp.reset(); 154 } 155 } 156 157 const lldb::ProcessSP & 158 Target::CreateProcess (Listener &listener, const char *plugin_name, const FileSpec *crash_file) 159 { 160 DeleteCurrentProcess (); 161 m_process_sp = Process::FindPlugin(*this, plugin_name, listener, crash_file); 162 return m_process_sp; 163 } 164 165 const lldb::ProcessSP & 166 Target::GetProcessSP () const 167 { 168 return m_process_sp; 169 } 170 171 void 172 Target::Destroy() 173 { 174 Mutex::Locker locker (m_mutex); 175 m_valid = false; 176 DeleteCurrentProcess (); 177 m_platform_sp.reset(); 178 m_arch.Clear(); 179 m_images.Clear(); 180 m_section_load_list.Clear(); 181 const bool notify = false; 182 m_breakpoint_list.RemoveAll(notify); 183 m_internal_breakpoint_list.RemoveAll(notify); 184 m_last_created_breakpoint.reset(); 185 m_last_created_watchpoint.reset(); 186 m_search_filter_sp.reset(); 187 m_image_search_paths.Clear(notify); 188 m_scratch_ast_context_ap.reset(); 189 m_scratch_ast_source_ap.reset(); 190 m_ast_importer_ap.reset(); 191 m_persistent_variables.Clear(); 192 m_stop_hooks.clear(); 193 m_stop_hook_next_id = 0; 194 m_suppress_stop_hooks = false; 195 m_suppress_synthetic_value = false; 196 } 197 198 199 BreakpointList & 200 Target::GetBreakpointList(bool internal) 201 { 202 if (internal) 203 return m_internal_breakpoint_list; 204 else 205 return m_breakpoint_list; 206 } 207 208 const BreakpointList & 209 Target::GetBreakpointList(bool internal) const 210 { 211 if (internal) 212 return m_internal_breakpoint_list; 213 else 214 return m_breakpoint_list; 215 } 216 217 BreakpointSP 218 Target::GetBreakpointByID (break_id_t break_id) 219 { 220 BreakpointSP bp_sp; 221 222 if (LLDB_BREAK_ID_IS_INTERNAL (break_id)) 223 bp_sp = m_internal_breakpoint_list.FindBreakpointByID (break_id); 224 else 225 bp_sp = m_breakpoint_list.FindBreakpointByID (break_id); 226 227 return bp_sp; 228 } 229 230 BreakpointSP 231 Target::CreateSourceRegexBreakpoint (const FileSpecList *containingModules, 232 const FileSpecList *source_file_spec_list, 233 RegularExpression &source_regex, 234 bool internal) 235 { 236 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList (containingModules, source_file_spec_list)); 237 BreakpointResolverSP resolver_sp(new BreakpointResolverFileRegex (NULL, source_regex)); 238 return CreateBreakpoint (filter_sp, resolver_sp, internal); 239 } 240 241 242 BreakpointSP 243 Target::CreateBreakpoint (const FileSpecList *containingModules, 244 const FileSpec &file, 245 uint32_t line_no, 246 LazyBool check_inlines, 247 LazyBool skip_prologue, 248 bool internal) 249 { 250 SearchFilterSP filter_sp(GetSearchFilterForModuleList (containingModules)); 251 252 if (check_inlines == eLazyBoolCalculate) 253 { 254 const InlineStrategy inline_strategy = GetInlineStrategy(); 255 switch (inline_strategy) 256 { 257 case eInlineBreakpointsNever: 258 check_inlines = eLazyBoolNo; 259 break; 260 261 case eInlineBreakpointsHeaders: 262 if (file.IsSourceImplementationFile()) 263 check_inlines = eLazyBoolNo; 264 else 265 check_inlines = eLazyBoolYes; 266 break; 267 268 case eInlineBreakpointsAlways: 269 check_inlines = eLazyBoolYes; 270 break; 271 } 272 } 273 BreakpointResolverSP resolver_sp(new BreakpointResolverFileLine (NULL, 274 file, 275 line_no, 276 check_inlines, 277 skip_prologue == eLazyBoolCalculate ? GetSkipPrologue() : skip_prologue)); 278 return CreateBreakpoint (filter_sp, resolver_sp, internal); 279 } 280 281 282 BreakpointSP 283 Target::CreateBreakpoint (lldb::addr_t addr, bool internal) 284 { 285 Address so_addr; 286 // Attempt to resolve our load address if possible, though it is ok if 287 // it doesn't resolve to section/offset. 288 289 // Try and resolve as a load address if possible 290 m_section_load_list.ResolveLoadAddress(addr, so_addr); 291 if (!so_addr.IsValid()) 292 { 293 // The address didn't resolve, so just set this as an absolute address 294 so_addr.SetOffset (addr); 295 } 296 BreakpointSP bp_sp (CreateBreakpoint(so_addr, internal)); 297 return bp_sp; 298 } 299 300 BreakpointSP 301 Target::CreateBreakpoint (Address &addr, bool internal) 302 { 303 SearchFilterSP filter_sp(new SearchFilterForNonModuleSpecificSearches (shared_from_this())); 304 BreakpointResolverSP resolver_sp (new BreakpointResolverAddress (NULL, addr)); 305 return CreateBreakpoint (filter_sp, resolver_sp, internal); 306 } 307 308 BreakpointSP 309 Target::CreateBreakpoint (const FileSpecList *containingModules, 310 const FileSpecList *containingSourceFiles, 311 const char *func_name, 312 uint32_t func_name_type_mask, 313 LazyBool skip_prologue, 314 bool internal) 315 { 316 BreakpointSP bp_sp; 317 if (func_name) 318 { 319 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList (containingModules, containingSourceFiles)); 320 321 BreakpointResolverSP resolver_sp (new BreakpointResolverName (NULL, 322 func_name, 323 func_name_type_mask, 324 Breakpoint::Exact, 325 skip_prologue == eLazyBoolCalculate ? GetSkipPrologue() : skip_prologue)); 326 bp_sp = CreateBreakpoint (filter_sp, resolver_sp, internal); 327 } 328 return bp_sp; 329 } 330 331 lldb::BreakpointSP 332 Target::CreateBreakpoint (const FileSpecList *containingModules, 333 const FileSpecList *containingSourceFiles, 334 const std::vector<std::string> &func_names, 335 uint32_t func_name_type_mask, 336 LazyBool skip_prologue, 337 bool internal) 338 { 339 BreakpointSP bp_sp; 340 size_t num_names = func_names.size(); 341 if (num_names > 0) 342 { 343 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList (containingModules, containingSourceFiles)); 344 345 BreakpointResolverSP resolver_sp (new BreakpointResolverName (NULL, 346 func_names, 347 func_name_type_mask, 348 skip_prologue == eLazyBoolCalculate ? GetSkipPrologue() : skip_prologue)); 349 bp_sp = CreateBreakpoint (filter_sp, resolver_sp, internal); 350 } 351 return bp_sp; 352 } 353 354 BreakpointSP 355 Target::CreateBreakpoint (const FileSpecList *containingModules, 356 const FileSpecList *containingSourceFiles, 357 const char *func_names[], 358 size_t num_names, 359 uint32_t func_name_type_mask, 360 LazyBool skip_prologue, 361 bool internal) 362 { 363 BreakpointSP bp_sp; 364 if (num_names > 0) 365 { 366 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList (containingModules, containingSourceFiles)); 367 368 BreakpointResolverSP resolver_sp (new BreakpointResolverName (NULL, 369 func_names, 370 num_names, 371 func_name_type_mask, 372 skip_prologue == eLazyBoolCalculate ? GetSkipPrologue() : skip_prologue)); 373 bp_sp = CreateBreakpoint (filter_sp, resolver_sp, internal); 374 } 375 return bp_sp; 376 } 377 378 SearchFilterSP 379 Target::GetSearchFilterForModule (const FileSpec *containingModule) 380 { 381 SearchFilterSP filter_sp; 382 if (containingModule != NULL) 383 { 384 // TODO: We should look into sharing module based search filters 385 // across many breakpoints like we do for the simple target based one 386 filter_sp.reset (new SearchFilterByModule (shared_from_this(), *containingModule)); 387 } 388 else 389 { 390 if (m_search_filter_sp.get() == NULL) 391 m_search_filter_sp.reset (new SearchFilterForNonModuleSpecificSearches (shared_from_this())); 392 filter_sp = m_search_filter_sp; 393 } 394 return filter_sp; 395 } 396 397 SearchFilterSP 398 Target::GetSearchFilterForModuleList (const FileSpecList *containingModules) 399 { 400 SearchFilterSP filter_sp; 401 if (containingModules && containingModules->GetSize() != 0) 402 { 403 // TODO: We should look into sharing module based search filters 404 // across many breakpoints like we do for the simple target based one 405 filter_sp.reset (new SearchFilterByModuleList (shared_from_this(), *containingModules)); 406 } 407 else 408 { 409 if (m_search_filter_sp.get() == NULL) 410 m_search_filter_sp.reset (new SearchFilterForNonModuleSpecificSearches (shared_from_this())); 411 filter_sp = m_search_filter_sp; 412 } 413 return filter_sp; 414 } 415 416 SearchFilterSP 417 Target::GetSearchFilterForModuleAndCUList (const FileSpecList *containingModules, 418 const FileSpecList *containingSourceFiles) 419 { 420 if (containingSourceFiles == NULL || containingSourceFiles->GetSize() == 0) 421 return GetSearchFilterForModuleList(containingModules); 422 423 SearchFilterSP filter_sp; 424 if (containingModules == NULL) 425 { 426 // We could make a special "CU List only SearchFilter". Better yet was if these could be composable, 427 // but that will take a little reworking. 428 429 filter_sp.reset (new SearchFilterByModuleListAndCU (shared_from_this(), FileSpecList(), *containingSourceFiles)); 430 } 431 else 432 { 433 filter_sp.reset (new SearchFilterByModuleListAndCU (shared_from_this(), *containingModules, *containingSourceFiles)); 434 } 435 return filter_sp; 436 } 437 438 BreakpointSP 439 Target::CreateFuncRegexBreakpoint (const FileSpecList *containingModules, 440 const FileSpecList *containingSourceFiles, 441 RegularExpression &func_regex, 442 LazyBool skip_prologue, 443 bool internal) 444 { 445 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList (containingModules, containingSourceFiles)); 446 BreakpointResolverSP resolver_sp(new BreakpointResolverName (NULL, 447 func_regex, 448 skip_prologue == eLazyBoolCalculate ? GetSkipPrologue() : skip_prologue)); 449 450 return CreateBreakpoint (filter_sp, resolver_sp, internal); 451 } 452 453 lldb::BreakpointSP 454 Target::CreateExceptionBreakpoint (enum lldb::LanguageType language, bool catch_bp, bool throw_bp, bool internal) 455 { 456 return LanguageRuntime::CreateExceptionBreakpoint (*this, language, catch_bp, throw_bp, internal); 457 } 458 459 BreakpointSP 460 Target::CreateBreakpoint (SearchFilterSP &filter_sp, BreakpointResolverSP &resolver_sp, bool internal) 461 { 462 BreakpointSP bp_sp; 463 if (filter_sp && resolver_sp) 464 { 465 bp_sp.reset(new Breakpoint (*this, filter_sp, resolver_sp)); 466 resolver_sp->SetBreakpoint (bp_sp.get()); 467 468 if (internal) 469 m_internal_breakpoint_list.Add (bp_sp, false); 470 else 471 m_breakpoint_list.Add (bp_sp, true); 472 473 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS)); 474 if (log) 475 { 476 StreamString s; 477 bp_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose); 478 log->Printf ("Target::%s (internal = %s) => break_id = %s\n", __FUNCTION__, internal ? "yes" : "no", s.GetData()); 479 } 480 481 bp_sp->ResolveBreakpoint(); 482 } 483 484 if (!internal && bp_sp) 485 { 486 m_last_created_breakpoint = bp_sp; 487 } 488 489 return bp_sp; 490 } 491 492 bool 493 Target::ProcessIsValid() 494 { 495 return (m_process_sp && m_process_sp->IsAlive()); 496 } 497 498 static bool 499 CheckIfWatchpointsExhausted(Target *target, Error &error) 500 { 501 uint32_t num_supported_hardware_watchpoints; 502 Error rc = target->GetProcessSP()->GetWatchpointSupportInfo(num_supported_hardware_watchpoints); 503 if (rc.Success()) 504 { 505 uint32_t num_current_watchpoints = target->GetWatchpointList().GetSize(); 506 if (num_current_watchpoints >= num_supported_hardware_watchpoints) 507 error.SetErrorStringWithFormat("number of supported hardware watchpoints (%u) has been reached", 508 num_supported_hardware_watchpoints); 509 } 510 return false; 511 } 512 513 // See also Watchpoint::SetWatchpointType(uint32_t type) and 514 // the OptionGroupWatchpoint::WatchType enum type. 515 WatchpointSP 516 Target::CreateWatchpoint(lldb::addr_t addr, size_t size, uint32_t type, Error &error) 517 { 518 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS)); 519 if (log) 520 log->Printf("Target::%s (addr = 0x%8.8llx size = %zu type = %u)\n", 521 __FUNCTION__, addr, size, type); 522 523 WatchpointSP wp_sp; 524 if (!ProcessIsValid()) 525 { 526 error.SetErrorString("process is not alive"); 527 return wp_sp; 528 } 529 if (addr == LLDB_INVALID_ADDRESS || size == 0) 530 { 531 if (size == 0) 532 error.SetErrorString("cannot set a watchpoint with watch_size of 0"); 533 else 534 error.SetErrorStringWithFormat("invalid watch address: %llu", addr); 535 return wp_sp; 536 } 537 538 // Currently we only support one watchpoint per address, with total number 539 // of watchpoints limited by the hardware which the inferior is running on. 540 541 // Grab the list mutex while doing operations. 542 Mutex::Locker locker; 543 this->GetWatchpointList().GetListMutex(locker); 544 WatchpointSP matched_sp = m_watchpoint_list.FindByAddress(addr); 545 if (matched_sp) 546 { 547 size_t old_size = matched_sp->GetByteSize(); 548 uint32_t old_type = 549 (matched_sp->WatchpointRead() ? LLDB_WATCH_TYPE_READ : 0) | 550 (matched_sp->WatchpointWrite() ? LLDB_WATCH_TYPE_WRITE : 0); 551 // Return the existing watchpoint if both size and type match. 552 if (size == old_size && type == old_type) { 553 wp_sp = matched_sp; 554 wp_sp->SetEnabled(false); 555 } else { 556 // Nil the matched watchpoint; we will be creating a new one. 557 m_process_sp->DisableWatchpoint(matched_sp.get()); 558 m_watchpoint_list.Remove(matched_sp->GetID()); 559 } 560 } 561 562 if (!wp_sp) { 563 Watchpoint *new_wp = new Watchpoint(addr, size); 564 if (!new_wp) { 565 printf("Watchpoint ctor failed, out of memory?\n"); 566 return wp_sp; 567 } 568 new_wp->SetWatchpointType(type); 569 new_wp->SetTarget(this); 570 wp_sp.reset(new_wp); 571 m_watchpoint_list.Add(wp_sp); 572 } 573 574 error = m_process_sp->EnableWatchpoint(wp_sp.get()); 575 if (log) 576 log->Printf("Target::%s (creation of watchpoint %s with id = %u)\n", 577 __FUNCTION__, 578 error.Success() ? "succeeded" : "failed", 579 wp_sp->GetID()); 580 581 if (error.Fail()) { 582 // Enabling the watchpoint on the device side failed. 583 // Remove the said watchpoint from the list maintained by the target instance. 584 m_watchpoint_list.Remove(wp_sp->GetID()); 585 // See if we could provide more helpful error message. 586 if (!CheckIfWatchpointsExhausted(this, error)) 587 { 588 if (!OptionGroupWatchpoint::IsWatchSizeSupported(size)) 589 error.SetErrorStringWithFormat("watch size of %lu is not supported", size); 590 } 591 wp_sp.reset(); 592 } 593 else 594 m_last_created_watchpoint = wp_sp; 595 return wp_sp; 596 } 597 598 void 599 Target::RemoveAllBreakpoints (bool internal_also) 600 { 601 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS)); 602 if (log) 603 log->Printf ("Target::%s (internal_also = %s)\n", __FUNCTION__, internal_also ? "yes" : "no"); 604 605 m_breakpoint_list.RemoveAll (true); 606 if (internal_also) 607 m_internal_breakpoint_list.RemoveAll (false); 608 609 m_last_created_breakpoint.reset(); 610 } 611 612 void 613 Target::DisableAllBreakpoints (bool internal_also) 614 { 615 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS)); 616 if (log) 617 log->Printf ("Target::%s (internal_also = %s)\n", __FUNCTION__, internal_also ? "yes" : "no"); 618 619 m_breakpoint_list.SetEnabledAll (false); 620 if (internal_also) 621 m_internal_breakpoint_list.SetEnabledAll (false); 622 } 623 624 void 625 Target::EnableAllBreakpoints (bool internal_also) 626 { 627 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS)); 628 if (log) 629 log->Printf ("Target::%s (internal_also = %s)\n", __FUNCTION__, internal_also ? "yes" : "no"); 630 631 m_breakpoint_list.SetEnabledAll (true); 632 if (internal_also) 633 m_internal_breakpoint_list.SetEnabledAll (true); 634 } 635 636 bool 637 Target::RemoveBreakpointByID (break_id_t break_id) 638 { 639 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS)); 640 if (log) 641 log->Printf ("Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__, break_id, LLDB_BREAK_ID_IS_INTERNAL (break_id) ? "yes" : "no"); 642 643 if (DisableBreakpointByID (break_id)) 644 { 645 if (LLDB_BREAK_ID_IS_INTERNAL (break_id)) 646 m_internal_breakpoint_list.Remove(break_id, false); 647 else 648 { 649 if (m_last_created_breakpoint) 650 { 651 if (m_last_created_breakpoint->GetID() == break_id) 652 m_last_created_breakpoint.reset(); 653 } 654 m_breakpoint_list.Remove(break_id, true); 655 } 656 return true; 657 } 658 return false; 659 } 660 661 bool 662 Target::DisableBreakpointByID (break_id_t break_id) 663 { 664 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS)); 665 if (log) 666 log->Printf ("Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__, break_id, LLDB_BREAK_ID_IS_INTERNAL (break_id) ? "yes" : "no"); 667 668 BreakpointSP bp_sp; 669 670 if (LLDB_BREAK_ID_IS_INTERNAL (break_id)) 671 bp_sp = m_internal_breakpoint_list.FindBreakpointByID (break_id); 672 else 673 bp_sp = m_breakpoint_list.FindBreakpointByID (break_id); 674 if (bp_sp) 675 { 676 bp_sp->SetEnabled (false); 677 return true; 678 } 679 return false; 680 } 681 682 bool 683 Target::EnableBreakpointByID (break_id_t break_id) 684 { 685 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS)); 686 if (log) 687 log->Printf ("Target::%s (break_id = %i, internal = %s)\n", 688 __FUNCTION__, 689 break_id, 690 LLDB_BREAK_ID_IS_INTERNAL (break_id) ? "yes" : "no"); 691 692 BreakpointSP bp_sp; 693 694 if (LLDB_BREAK_ID_IS_INTERNAL (break_id)) 695 bp_sp = m_internal_breakpoint_list.FindBreakpointByID (break_id); 696 else 697 bp_sp = m_breakpoint_list.FindBreakpointByID (break_id); 698 699 if (bp_sp) 700 { 701 bp_sp->SetEnabled (true); 702 return true; 703 } 704 return false; 705 } 706 707 // The flag 'end_to_end', default to true, signifies that the operation is 708 // performed end to end, for both the debugger and the debuggee. 709 710 // Assumption: Caller holds the list mutex lock for m_watchpoint_list for end 711 // to end operations. 712 bool 713 Target::RemoveAllWatchpoints (bool end_to_end) 714 { 715 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS)); 716 if (log) 717 log->Printf ("Target::%s\n", __FUNCTION__); 718 719 if (!end_to_end) { 720 m_watchpoint_list.RemoveAll(); 721 return true; 722 } 723 724 // Otherwise, it's an end to end operation. 725 726 if (!ProcessIsValid()) 727 return false; 728 729 size_t num_watchpoints = m_watchpoint_list.GetSize(); 730 for (size_t i = 0; i < num_watchpoints; ++i) 731 { 732 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i); 733 if (!wp_sp) 734 return false; 735 736 Error rc = m_process_sp->DisableWatchpoint(wp_sp.get()); 737 if (rc.Fail()) 738 return false; 739 } 740 m_watchpoint_list.RemoveAll (); 741 return true; // Success! 742 } 743 744 // Assumption: Caller holds the list mutex lock for m_watchpoint_list for end to 745 // end operations. 746 bool 747 Target::DisableAllWatchpoints (bool end_to_end) 748 { 749 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS)); 750 if (log) 751 log->Printf ("Target::%s\n", __FUNCTION__); 752 753 if (!end_to_end) { 754 m_watchpoint_list.SetEnabledAll(false); 755 return true; 756 } 757 758 // Otherwise, it's an end to end operation. 759 760 if (!ProcessIsValid()) 761 return false; 762 763 size_t num_watchpoints = m_watchpoint_list.GetSize(); 764 for (size_t i = 0; i < num_watchpoints; ++i) 765 { 766 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i); 767 if (!wp_sp) 768 return false; 769 770 Error rc = m_process_sp->DisableWatchpoint(wp_sp.get()); 771 if (rc.Fail()) 772 return false; 773 } 774 return true; // Success! 775 } 776 777 // Assumption: Caller holds the list mutex lock for m_watchpoint_list for end to 778 // end operations. 779 bool 780 Target::EnableAllWatchpoints (bool end_to_end) 781 { 782 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS)); 783 if (log) 784 log->Printf ("Target::%s\n", __FUNCTION__); 785 786 if (!end_to_end) { 787 m_watchpoint_list.SetEnabledAll(true); 788 return true; 789 } 790 791 // Otherwise, it's an end to end operation. 792 793 if (!ProcessIsValid()) 794 return false; 795 796 size_t num_watchpoints = m_watchpoint_list.GetSize(); 797 for (size_t i = 0; i < num_watchpoints; ++i) 798 { 799 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i); 800 if (!wp_sp) 801 return false; 802 803 Error rc = m_process_sp->EnableWatchpoint(wp_sp.get()); 804 if (rc.Fail()) 805 return false; 806 } 807 return true; // Success! 808 } 809 810 // Assumption: Caller holds the list mutex lock for m_watchpoint_list. 811 bool 812 Target::ClearAllWatchpointHitCounts () 813 { 814 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS)); 815 if (log) 816 log->Printf ("Target::%s\n", __FUNCTION__); 817 818 size_t num_watchpoints = m_watchpoint_list.GetSize(); 819 for (size_t i = 0; i < num_watchpoints; ++i) 820 { 821 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i); 822 if (!wp_sp) 823 return false; 824 825 wp_sp->ResetHitCount(); 826 } 827 return true; // Success! 828 } 829 830 // Assumption: Caller holds the list mutex lock for m_watchpoint_list 831 // during these operations. 832 bool 833 Target::IgnoreAllWatchpoints (uint32_t ignore_count) 834 { 835 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS)); 836 if (log) 837 log->Printf ("Target::%s\n", __FUNCTION__); 838 839 if (!ProcessIsValid()) 840 return false; 841 842 size_t num_watchpoints = m_watchpoint_list.GetSize(); 843 for (size_t i = 0; i < num_watchpoints; ++i) 844 { 845 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i); 846 if (!wp_sp) 847 return false; 848 849 wp_sp->SetIgnoreCount(ignore_count); 850 } 851 return true; // Success! 852 } 853 854 // Assumption: Caller holds the list mutex lock for m_watchpoint_list. 855 bool 856 Target::DisableWatchpointByID (lldb::watch_id_t watch_id) 857 { 858 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS)); 859 if (log) 860 log->Printf ("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id); 861 862 if (!ProcessIsValid()) 863 return false; 864 865 WatchpointSP wp_sp = m_watchpoint_list.FindByID (watch_id); 866 if (wp_sp) 867 { 868 Error rc = m_process_sp->DisableWatchpoint(wp_sp.get()); 869 if (rc.Success()) 870 return true; 871 872 // Else, fallthrough. 873 } 874 return false; 875 } 876 877 // Assumption: Caller holds the list mutex lock for m_watchpoint_list. 878 bool 879 Target::EnableWatchpointByID (lldb::watch_id_t watch_id) 880 { 881 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS)); 882 if (log) 883 log->Printf ("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id); 884 885 if (!ProcessIsValid()) 886 return false; 887 888 WatchpointSP wp_sp = m_watchpoint_list.FindByID (watch_id); 889 if (wp_sp) 890 { 891 Error rc = m_process_sp->EnableWatchpoint(wp_sp.get()); 892 if (rc.Success()) 893 return true; 894 895 // Else, fallthrough. 896 } 897 return false; 898 } 899 900 // Assumption: Caller holds the list mutex lock for m_watchpoint_list. 901 bool 902 Target::RemoveWatchpointByID (lldb::watch_id_t watch_id) 903 { 904 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS)); 905 if (log) 906 log->Printf ("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id); 907 908 if (DisableWatchpointByID (watch_id)) 909 { 910 m_watchpoint_list.Remove(watch_id); 911 return true; 912 } 913 return false; 914 } 915 916 // Assumption: Caller holds the list mutex lock for m_watchpoint_list. 917 bool 918 Target::IgnoreWatchpointByID (lldb::watch_id_t watch_id, uint32_t ignore_count) 919 { 920 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS)); 921 if (log) 922 log->Printf ("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id); 923 924 if (!ProcessIsValid()) 925 return false; 926 927 WatchpointSP wp_sp = m_watchpoint_list.FindByID (watch_id); 928 if (wp_sp) 929 { 930 wp_sp->SetIgnoreCount(ignore_count); 931 return true; 932 } 933 return false; 934 } 935 936 ModuleSP 937 Target::GetExecutableModule () 938 { 939 return m_images.GetModuleAtIndex(0); 940 } 941 942 Module* 943 Target::GetExecutableModulePointer () 944 { 945 return m_images.GetModulePointerAtIndex(0); 946 } 947 948 void 949 Target::SetExecutableModule (ModuleSP& executable_sp, bool get_dependent_files) 950 { 951 m_images.Clear(); 952 m_scratch_ast_context_ap.reset(); 953 m_scratch_ast_source_ap.reset(); 954 m_ast_importer_ap.reset(); 955 956 if (executable_sp.get()) 957 { 958 Timer scoped_timer (__PRETTY_FUNCTION__, 959 "Target::SetExecutableModule (executable = '%s/%s')", 960 executable_sp->GetFileSpec().GetDirectory().AsCString(), 961 executable_sp->GetFileSpec().GetFilename().AsCString()); 962 963 m_images.Append(executable_sp); // The first image is our exectuable file 964 965 // If we haven't set an architecture yet, reset our architecture based on what we found in the executable module. 966 if (!m_arch.IsValid()) 967 m_arch = executable_sp->GetArchitecture(); 968 969 FileSpecList dependent_files; 970 ObjectFile *executable_objfile = executable_sp->GetObjectFile(); 971 972 if (executable_objfile && get_dependent_files) 973 { 974 executable_objfile->GetDependentModules(dependent_files); 975 for (uint32_t i=0; i<dependent_files.GetSize(); i++) 976 { 977 FileSpec dependent_file_spec (dependent_files.GetFileSpecPointerAtIndex(i)); 978 FileSpec platform_dependent_file_spec; 979 if (m_platform_sp) 980 m_platform_sp->GetFile (dependent_file_spec, NULL, platform_dependent_file_spec); 981 else 982 platform_dependent_file_spec = dependent_file_spec; 983 984 ModuleSpec module_spec (platform_dependent_file_spec, m_arch); 985 ModuleSP image_module_sp(GetSharedModule (module_spec)); 986 if (image_module_sp.get()) 987 { 988 ObjectFile *objfile = image_module_sp->GetObjectFile(); 989 if (objfile) 990 objfile->GetDependentModules(dependent_files); 991 } 992 } 993 } 994 } 995 } 996 997 998 bool 999 Target::SetArchitecture (const ArchSpec &arch_spec) 1000 { 1001 if (m_arch == arch_spec || !m_arch.IsValid()) 1002 { 1003 // If we haven't got a valid arch spec, or the architectures are 1004 // compatible, so just update the architecture. Architectures can be 1005 // equal, yet the triple OS and vendor might change, so we need to do 1006 // the assignment here just in case. 1007 m_arch = arch_spec; 1008 return true; 1009 } 1010 else 1011 { 1012 // If we have an executable file, try to reset the executable to the desired architecture 1013 m_arch = arch_spec; 1014 ModuleSP executable_sp = GetExecutableModule (); 1015 m_images.Clear(); 1016 m_scratch_ast_context_ap.reset(); 1017 m_scratch_ast_source_ap.reset(); 1018 m_ast_importer_ap.reset(); 1019 // Need to do something about unsetting breakpoints. 1020 1021 if (executable_sp) 1022 { 1023 ModuleSpec module_spec (executable_sp->GetFileSpec(), arch_spec); 1024 Error error = ModuleList::GetSharedModule (module_spec, 1025 executable_sp, 1026 &GetExecutableSearchPaths(), 1027 NULL, 1028 NULL); 1029 1030 if (!error.Fail() && executable_sp) 1031 { 1032 SetExecutableModule (executable_sp, true); 1033 return true; 1034 } 1035 } 1036 } 1037 return false; 1038 } 1039 1040 void 1041 Target::ModuleAdded (ModuleSP &module_sp) 1042 { 1043 // A module is being added to this target for the first time 1044 ModuleList module_list; 1045 module_list.Append(module_sp); 1046 ModulesDidLoad (module_list); 1047 } 1048 1049 void 1050 Target::ModuleUpdated (ModuleSP &old_module_sp, ModuleSP &new_module_sp) 1051 { 1052 // A module is replacing an already added module 1053 m_breakpoint_list.UpdateBreakpointsWhenModuleIsReplaced(old_module_sp, new_module_sp); 1054 } 1055 1056 void 1057 Target::ModulesDidLoad (ModuleList &module_list) 1058 { 1059 m_breakpoint_list.UpdateBreakpoints (module_list, true); 1060 // TODO: make event data that packages up the module_list 1061 BroadcastEvent (eBroadcastBitModulesLoaded, NULL); 1062 } 1063 1064 void 1065 Target::ModulesDidUnload (ModuleList &module_list) 1066 { 1067 m_breakpoint_list.UpdateBreakpoints (module_list, false); 1068 1069 // Remove the images from the target image list 1070 m_images.Remove(module_list); 1071 1072 // TODO: make event data that packages up the module_list 1073 BroadcastEvent (eBroadcastBitModulesUnloaded, NULL); 1074 } 1075 1076 1077 bool 1078 Target::ModuleIsExcludedForNonModuleSpecificSearches (const FileSpec &module_file_spec) 1079 { 1080 1081 if (GetBreakpointsConsultPlatformAvoidList()) 1082 { 1083 ModuleList matchingModules; 1084 ModuleSpec module_spec (module_file_spec); 1085 size_t num_modules = GetImages().FindModules(module_spec, matchingModules); 1086 1087 // If there is more than one module for this file spec, only return true if ALL the modules are on the 1088 // black list. 1089 if (num_modules > 0) 1090 { 1091 for (int i = 0; i < num_modules; i++) 1092 { 1093 if (!ModuleIsExcludedForNonModuleSpecificSearches (matchingModules.GetModuleAtIndex(i))) 1094 return false; 1095 } 1096 return true; 1097 } 1098 } 1099 return false; 1100 } 1101 1102 bool 1103 Target::ModuleIsExcludedForNonModuleSpecificSearches (const lldb::ModuleSP &module_sp) 1104 { 1105 if (GetBreakpointsConsultPlatformAvoidList()) 1106 { 1107 if (m_platform_sp) 1108 return m_platform_sp->ModuleIsExcludedForNonModuleSpecificSearches (*this, module_sp); 1109 } 1110 return false; 1111 } 1112 1113 size_t 1114 Target::ReadMemoryFromFileCache (const Address& addr, void *dst, size_t dst_len, Error &error) 1115 { 1116 SectionSP section_sp (addr.GetSection()); 1117 if (section_sp) 1118 { 1119 // If the contents of this section are encrypted, the on-disk file is unusuable. Read only from live memory. 1120 if (section_sp->IsEncrypted()) 1121 { 1122 error.SetErrorString("section is encrypted"); 1123 return 0; 1124 } 1125 ModuleSP module_sp (section_sp->GetModule()); 1126 if (module_sp) 1127 { 1128 ObjectFile *objfile = section_sp->GetModule()->GetObjectFile(); 1129 if (objfile) 1130 { 1131 size_t bytes_read = objfile->ReadSectionData (section_sp.get(), 1132 addr.GetOffset(), 1133 dst, 1134 dst_len); 1135 if (bytes_read > 0) 1136 return bytes_read; 1137 else 1138 error.SetErrorStringWithFormat("error reading data from section %s", section_sp->GetName().GetCString()); 1139 } 1140 else 1141 error.SetErrorString("address isn't from a object file"); 1142 } 1143 else 1144 error.SetErrorString("address isn't in a module"); 1145 } 1146 else 1147 error.SetErrorString("address doesn't contain a section that points to a section in a object file"); 1148 1149 return 0; 1150 } 1151 1152 size_t 1153 Target::ReadMemory (const Address& addr, 1154 bool prefer_file_cache, 1155 void *dst, 1156 size_t dst_len, 1157 Error &error, 1158 lldb::addr_t *load_addr_ptr) 1159 { 1160 error.Clear(); 1161 1162 // if we end up reading this from process memory, we will fill this 1163 // with the actual load address 1164 if (load_addr_ptr) 1165 *load_addr_ptr = LLDB_INVALID_ADDRESS; 1166 1167 size_t bytes_read = 0; 1168 1169 addr_t load_addr = LLDB_INVALID_ADDRESS; 1170 addr_t file_addr = LLDB_INVALID_ADDRESS; 1171 Address resolved_addr; 1172 if (!addr.IsSectionOffset()) 1173 { 1174 if (m_section_load_list.IsEmpty()) 1175 { 1176 // No sections are loaded, so we must assume we are not running 1177 // yet and anything we are given is a file address. 1178 file_addr = addr.GetOffset(); // "addr" doesn't have a section, so its offset is the file address 1179 m_images.ResolveFileAddress (file_addr, resolved_addr); 1180 } 1181 else 1182 { 1183 // We have at least one section loaded. This can be becuase 1184 // we have manually loaded some sections with "target modules load ..." 1185 // or because we have have a live process that has sections loaded 1186 // through the dynamic loader 1187 load_addr = addr.GetOffset(); // "addr" doesn't have a section, so its offset is the load address 1188 m_section_load_list.ResolveLoadAddress (load_addr, resolved_addr); 1189 } 1190 } 1191 if (!resolved_addr.IsValid()) 1192 resolved_addr = addr; 1193 1194 1195 if (prefer_file_cache) 1196 { 1197 bytes_read = ReadMemoryFromFileCache (resolved_addr, dst, dst_len, error); 1198 if (bytes_read > 0) 1199 return bytes_read; 1200 } 1201 1202 if (ProcessIsValid()) 1203 { 1204 if (load_addr == LLDB_INVALID_ADDRESS) 1205 load_addr = resolved_addr.GetLoadAddress (this); 1206 1207 if (load_addr == LLDB_INVALID_ADDRESS) 1208 { 1209 ModuleSP addr_module_sp (resolved_addr.GetModule()); 1210 if (addr_module_sp && addr_module_sp->GetFileSpec()) 1211 error.SetErrorStringWithFormat("%s[0x%llx] can't be resolved, %s in not currently loaded", 1212 addr_module_sp->GetFileSpec().GetFilename().AsCString(), 1213 resolved_addr.GetFileAddress(), 1214 addr_module_sp->GetFileSpec().GetFilename().AsCString()); 1215 else 1216 error.SetErrorStringWithFormat("0x%llx can't be resolved", resolved_addr.GetFileAddress()); 1217 } 1218 else 1219 { 1220 bytes_read = m_process_sp->ReadMemory(load_addr, dst, dst_len, error); 1221 if (bytes_read != dst_len) 1222 { 1223 if (error.Success()) 1224 { 1225 if (bytes_read == 0) 1226 error.SetErrorStringWithFormat("read memory from 0x%llx failed", load_addr); 1227 else 1228 error.SetErrorStringWithFormat("only %zu of %zu bytes were read from memory at 0x%llx", bytes_read, dst_len, load_addr); 1229 } 1230 } 1231 if (bytes_read) 1232 { 1233 if (load_addr_ptr) 1234 *load_addr_ptr = load_addr; 1235 return bytes_read; 1236 } 1237 // If the address is not section offset we have an address that 1238 // doesn't resolve to any address in any currently loaded shared 1239 // libaries and we failed to read memory so there isn't anything 1240 // more we can do. If it is section offset, we might be able to 1241 // read cached memory from the object file. 1242 if (!resolved_addr.IsSectionOffset()) 1243 return 0; 1244 } 1245 } 1246 1247 if (!prefer_file_cache && resolved_addr.IsSectionOffset()) 1248 { 1249 // If we didn't already try and read from the object file cache, then 1250 // try it after failing to read from the process. 1251 return ReadMemoryFromFileCache (resolved_addr, dst, dst_len, error); 1252 } 1253 return 0; 1254 } 1255 1256 size_t 1257 Target::ReadScalarIntegerFromMemory (const Address& addr, 1258 bool prefer_file_cache, 1259 uint32_t byte_size, 1260 bool is_signed, 1261 Scalar &scalar, 1262 Error &error) 1263 { 1264 uint64_t uval; 1265 1266 if (byte_size <= sizeof(uval)) 1267 { 1268 size_t bytes_read = ReadMemory (addr, prefer_file_cache, &uval, byte_size, error); 1269 if (bytes_read == byte_size) 1270 { 1271 DataExtractor data (&uval, sizeof(uval), m_arch.GetByteOrder(), m_arch.GetAddressByteSize()); 1272 uint32_t offset = 0; 1273 if (byte_size <= 4) 1274 scalar = data.GetMaxU32 (&offset, byte_size); 1275 else 1276 scalar = data.GetMaxU64 (&offset, byte_size); 1277 1278 if (is_signed) 1279 scalar.SignExtend(byte_size * 8); 1280 return bytes_read; 1281 } 1282 } 1283 else 1284 { 1285 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size); 1286 } 1287 return 0; 1288 } 1289 1290 uint64_t 1291 Target::ReadUnsignedIntegerFromMemory (const Address& addr, 1292 bool prefer_file_cache, 1293 size_t integer_byte_size, 1294 uint64_t fail_value, 1295 Error &error) 1296 { 1297 Scalar scalar; 1298 if (ReadScalarIntegerFromMemory (addr, 1299 prefer_file_cache, 1300 integer_byte_size, 1301 false, 1302 scalar, 1303 error)) 1304 return scalar.ULongLong(fail_value); 1305 return fail_value; 1306 } 1307 1308 bool 1309 Target::ReadPointerFromMemory (const Address& addr, 1310 bool prefer_file_cache, 1311 Error &error, 1312 Address &pointer_addr) 1313 { 1314 Scalar scalar; 1315 if (ReadScalarIntegerFromMemory (addr, 1316 prefer_file_cache, 1317 m_arch.GetAddressByteSize(), 1318 false, 1319 scalar, 1320 error)) 1321 { 1322 addr_t pointer_vm_addr = scalar.ULongLong(LLDB_INVALID_ADDRESS); 1323 if (pointer_vm_addr != LLDB_INVALID_ADDRESS) 1324 { 1325 if (m_section_load_list.IsEmpty()) 1326 { 1327 // No sections are loaded, so we must assume we are not running 1328 // yet and anything we are given is a file address. 1329 m_images.ResolveFileAddress (pointer_vm_addr, pointer_addr); 1330 } 1331 else 1332 { 1333 // We have at least one section loaded. This can be becuase 1334 // we have manually loaded some sections with "target modules load ..." 1335 // or because we have have a live process that has sections loaded 1336 // through the dynamic loader 1337 m_section_load_list.ResolveLoadAddress (pointer_vm_addr, pointer_addr); 1338 } 1339 // We weren't able to resolve the pointer value, so just return 1340 // an address with no section 1341 if (!pointer_addr.IsValid()) 1342 pointer_addr.SetOffset (pointer_vm_addr); 1343 return true; 1344 1345 } 1346 } 1347 return false; 1348 } 1349 1350 ModuleSP 1351 Target::GetSharedModule (const ModuleSpec &module_spec, Error *error_ptr) 1352 { 1353 ModuleSP module_sp; 1354 1355 Error error; 1356 1357 // First see if we already have this module in our module list. If we do, then we're done, we don't need 1358 // to consult the shared modules list. But only do this if we are passed a UUID. 1359 1360 if (module_spec.GetUUID().IsValid()) 1361 module_sp = m_images.FindFirstModule(module_spec); 1362 1363 if (!module_sp) 1364 { 1365 ModuleSP old_module_sp; // This will get filled in if we have a new version of the library 1366 bool did_create_module = false; 1367 1368 // If there are image search path entries, try to use them first to acquire a suitable image. 1369 if (m_image_search_paths.GetSize()) 1370 { 1371 ModuleSpec transformed_spec (module_spec); 1372 if (m_image_search_paths.RemapPath (module_spec.GetFileSpec().GetDirectory(), transformed_spec.GetFileSpec().GetDirectory())) 1373 { 1374 transformed_spec.GetFileSpec().GetFilename() = module_spec.GetFileSpec().GetFilename(); 1375 error = ModuleList::GetSharedModule (transformed_spec, 1376 module_sp, 1377 &GetExecutableSearchPaths(), 1378 &old_module_sp, 1379 &did_create_module); 1380 } 1381 } 1382 1383 if (!module_sp) 1384 { 1385 // If we have a UUID, we can check our global shared module list in case 1386 // we already have it. If we don't have a valid UUID, then we can't since 1387 // the path in "module_spec" will be a platform path, and we will need to 1388 // let the platform find that file. For example, we could be asking for 1389 // "/usr/lib/dyld" and if we do not have a UUID, we don't want to pick 1390 // the local copy of "/usr/lib/dyld" since our platform could be a remote 1391 // platform that has its own "/usr/lib/dyld" in an SDK or in a local file 1392 // cache. 1393 if (module_spec.GetUUID().IsValid()) 1394 { 1395 // We have a UUID, it is OK to check the global module list... 1396 error = ModuleList::GetSharedModule (module_spec, 1397 module_sp, 1398 &GetExecutableSearchPaths(), 1399 &old_module_sp, 1400 &did_create_module); 1401 } 1402 1403 if (!module_sp) 1404 { 1405 // The platform is responsible for finding and caching an appropriate 1406 // module in the shared module cache. 1407 if (m_platform_sp) 1408 { 1409 FileSpec platform_file_spec; 1410 error = m_platform_sp->GetSharedModule (module_spec, 1411 module_sp, 1412 &GetExecutableSearchPaths(), 1413 &old_module_sp, 1414 &did_create_module); 1415 } 1416 else 1417 { 1418 error.SetErrorString("no platform is currently set"); 1419 } 1420 } 1421 } 1422 1423 // We found a module that wasn't in our target list. Let's make sure that there wasn't an equivalent 1424 // module in the list already, and if there was, let's remove it. 1425 if (module_sp) 1426 { 1427 // GetSharedModule is not guaranteed to find the old shared module, for instance 1428 // in the common case where you pass in the UUID, it is only going to find the one 1429 // module matching the UUID. In fact, it has no good way to know what the "old module" 1430 // relevant to this target is, since there might be many copies of a module with this file spec 1431 // in various running debug sessions, but only one of them will belong to this target. 1432 // So let's remove the UUID from the module list, and look in the target's module list. 1433 // Only do this if there is SOMETHING else in the module spec... 1434 if (!old_module_sp) 1435 { 1436 if (module_spec.GetUUID().IsValid() && !module_spec.GetFileSpec().GetFilename().IsEmpty() && !module_spec.GetFileSpec().GetDirectory().IsEmpty()) 1437 { 1438 ModuleSpec module_spec_copy(module_spec.GetFileSpec()); 1439 module_spec_copy.GetUUID().Clear(); 1440 1441 ModuleList found_modules; 1442 size_t num_found = m_images.FindModules (module_spec_copy, found_modules); 1443 if (num_found == 1) 1444 { 1445 old_module_sp = found_modules.GetModuleAtIndex(0); 1446 } 1447 } 1448 } 1449 1450 m_images.Append (module_sp); 1451 if (old_module_sp && m_images.GetIndexForModule (old_module_sp.get()) != LLDB_INVALID_INDEX32) 1452 { 1453 ModuleUpdated(old_module_sp, module_sp); 1454 m_images.Remove (old_module_sp); 1455 Module *old_module_ptr = old_module_sp.get(); 1456 old_module_sp.reset(); 1457 ModuleList::RemoveSharedModuleIfOrphaned (old_module_ptr); 1458 } 1459 else 1460 ModuleAdded(module_sp); 1461 } 1462 } 1463 if (error_ptr) 1464 *error_ptr = error; 1465 return module_sp; 1466 } 1467 1468 1469 TargetSP 1470 Target::CalculateTarget () 1471 { 1472 return shared_from_this(); 1473 } 1474 1475 ProcessSP 1476 Target::CalculateProcess () 1477 { 1478 return ProcessSP(); 1479 } 1480 1481 ThreadSP 1482 Target::CalculateThread () 1483 { 1484 return ThreadSP(); 1485 } 1486 1487 StackFrameSP 1488 Target::CalculateStackFrame () 1489 { 1490 return StackFrameSP(); 1491 } 1492 1493 void 1494 Target::CalculateExecutionContext (ExecutionContext &exe_ctx) 1495 { 1496 exe_ctx.Clear(); 1497 exe_ctx.SetTargetPtr(this); 1498 } 1499 1500 PathMappingList & 1501 Target::GetImageSearchPathList () 1502 { 1503 return m_image_search_paths; 1504 } 1505 1506 void 1507 Target::ImageSearchPathsChanged 1508 ( 1509 const PathMappingList &path_list, 1510 void *baton 1511 ) 1512 { 1513 Target *target = (Target *)baton; 1514 ModuleSP exe_module_sp (target->GetExecutableModule()); 1515 if (exe_module_sp) 1516 { 1517 target->m_images.Clear(); 1518 target->SetExecutableModule (exe_module_sp, true); 1519 } 1520 } 1521 1522 ClangASTContext * 1523 Target::GetScratchClangASTContext(bool create_on_demand) 1524 { 1525 // Now see if we know the target triple, and if so, create our scratch AST context: 1526 if (m_scratch_ast_context_ap.get() == NULL && m_arch.IsValid() && create_on_demand) 1527 { 1528 m_scratch_ast_context_ap.reset (new ClangASTContext(m_arch.GetTriple().str().c_str())); 1529 m_scratch_ast_source_ap.reset (new ClangASTSource(shared_from_this())); 1530 m_scratch_ast_source_ap->InstallASTContext(m_scratch_ast_context_ap->getASTContext()); 1531 llvm::OwningPtr<clang::ExternalASTSource> proxy_ast_source(m_scratch_ast_source_ap->CreateProxy()); 1532 m_scratch_ast_context_ap->SetExternalSource(proxy_ast_source); 1533 } 1534 return m_scratch_ast_context_ap.get(); 1535 } 1536 1537 ClangASTImporter * 1538 Target::GetClangASTImporter() 1539 { 1540 ClangASTImporter *ast_importer = m_ast_importer_ap.get(); 1541 1542 if (!ast_importer) 1543 { 1544 ast_importer = new ClangASTImporter(); 1545 m_ast_importer_ap.reset(ast_importer); 1546 } 1547 1548 return ast_importer; 1549 } 1550 1551 void 1552 Target::SettingsInitialize () 1553 { 1554 Process::SettingsInitialize (); 1555 } 1556 1557 void 1558 Target::SettingsTerminate () 1559 { 1560 Process::SettingsTerminate (); 1561 } 1562 1563 FileSpecList 1564 Target::GetDefaultExecutableSearchPaths () 1565 { 1566 TargetPropertiesSP properties_sp(Target::GetGlobalProperties()); 1567 if (properties_sp) 1568 return properties_sp->GetExecutableSearchPaths(); 1569 return FileSpecList(); 1570 } 1571 1572 ArchSpec 1573 Target::GetDefaultArchitecture () 1574 { 1575 TargetPropertiesSP properties_sp(Target::GetGlobalProperties()); 1576 if (properties_sp) 1577 return properties_sp->GetDefaultArchitecture(); 1578 return ArchSpec(); 1579 } 1580 1581 void 1582 Target::SetDefaultArchitecture (const ArchSpec &arch) 1583 { 1584 TargetPropertiesSP properties_sp(Target::GetGlobalProperties()); 1585 if (properties_sp) 1586 return properties_sp->SetDefaultArchitecture(arch); 1587 } 1588 1589 Target * 1590 Target::GetTargetFromContexts (const ExecutionContext *exe_ctx_ptr, const SymbolContext *sc_ptr) 1591 { 1592 // The target can either exist in the "process" of ExecutionContext, or in 1593 // the "target_sp" member of SymbolContext. This accessor helper function 1594 // will get the target from one of these locations. 1595 1596 Target *target = NULL; 1597 if (sc_ptr != NULL) 1598 target = sc_ptr->target_sp.get(); 1599 if (target == NULL && exe_ctx_ptr) 1600 target = exe_ctx_ptr->GetTargetPtr(); 1601 return target; 1602 } 1603 1604 ExecutionResults 1605 Target::EvaluateExpression 1606 ( 1607 const char *expr_cstr, 1608 StackFrame *frame, 1609 lldb_private::ExecutionPolicy execution_policy, 1610 bool coerce_to_id, 1611 bool unwind_on_error, 1612 bool keep_in_memory, 1613 lldb::DynamicValueType use_dynamic, 1614 lldb::ValueObjectSP &result_valobj_sp, 1615 uint32_t single_thread_timeout_usec 1616 ) 1617 { 1618 ExecutionResults execution_results = eExecutionSetupError; 1619 1620 result_valobj_sp.reset(); 1621 1622 if (expr_cstr == NULL || expr_cstr[0] == '\0') 1623 return execution_results; 1624 1625 // We shouldn't run stop hooks in expressions. 1626 // Be sure to reset this if you return anywhere within this function. 1627 bool old_suppress_value = m_suppress_stop_hooks; 1628 m_suppress_stop_hooks = true; 1629 1630 ExecutionContext exe_ctx; 1631 1632 const size_t expr_cstr_len = ::strlen (expr_cstr); 1633 1634 if (frame) 1635 { 1636 frame->CalculateExecutionContext(exe_ctx); 1637 Error error; 1638 const uint32_t expr_path_options = StackFrame::eExpressionPathOptionCheckPtrVsMember | 1639 StackFrame::eExpressionPathOptionsNoFragileObjcIvar | 1640 StackFrame::eExpressionPathOptionsNoSyntheticChildren; 1641 lldb::VariableSP var_sp; 1642 1643 // Make sure we don't have any things that we know a variable expression 1644 // won't be able to deal with before calling into it 1645 if (::strcspn (expr_cstr, "()+*&|!~<=/^%,?") == expr_cstr_len) 1646 { 1647 result_valobj_sp = frame->GetValueForVariableExpressionPath (expr_cstr, 1648 use_dynamic, 1649 expr_path_options, 1650 var_sp, 1651 error); 1652 // if this expression results in a bitfield, we give up and let the IR handle it 1653 if (result_valobj_sp && result_valobj_sp->IsBitfield()) 1654 result_valobj_sp.reset(); 1655 } 1656 } 1657 else if (m_process_sp) 1658 { 1659 m_process_sp->CalculateExecutionContext(exe_ctx); 1660 } 1661 else 1662 { 1663 CalculateExecutionContext(exe_ctx); 1664 } 1665 1666 if (result_valobj_sp) 1667 { 1668 execution_results = eExecutionCompleted; 1669 // We got a result from the frame variable expression path above... 1670 ConstString persistent_variable_name (m_persistent_variables.GetNextPersistentVariableName()); 1671 1672 lldb::ValueObjectSP const_valobj_sp; 1673 1674 // Check in case our value is already a constant value 1675 if (result_valobj_sp->GetIsConstant()) 1676 { 1677 const_valobj_sp = result_valobj_sp; 1678 const_valobj_sp->SetName (persistent_variable_name); 1679 } 1680 else 1681 { 1682 if (use_dynamic != lldb::eNoDynamicValues) 1683 { 1684 ValueObjectSP dynamic_sp = result_valobj_sp->GetDynamicValue(use_dynamic); 1685 if (dynamic_sp) 1686 result_valobj_sp = dynamic_sp; 1687 } 1688 1689 const_valobj_sp = result_valobj_sp->CreateConstantValue (persistent_variable_name); 1690 } 1691 1692 lldb::ValueObjectSP live_valobj_sp = result_valobj_sp; 1693 1694 result_valobj_sp = const_valobj_sp; 1695 1696 ClangExpressionVariableSP clang_expr_variable_sp(m_persistent_variables.CreatePersistentVariable(result_valobj_sp)); 1697 assert (clang_expr_variable_sp.get()); 1698 1699 // Set flags and live data as appropriate 1700 1701 const Value &result_value = live_valobj_sp->GetValue(); 1702 1703 switch (result_value.GetValueType()) 1704 { 1705 case Value::eValueTypeHostAddress: 1706 case Value::eValueTypeFileAddress: 1707 // we don't do anything with these for now 1708 break; 1709 case Value::eValueTypeScalar: 1710 clang_expr_variable_sp->m_flags |= ClangExpressionVariable::EVIsLLDBAllocated; 1711 clang_expr_variable_sp->m_flags |= ClangExpressionVariable::EVNeedsAllocation; 1712 break; 1713 case Value::eValueTypeLoadAddress: 1714 clang_expr_variable_sp->m_live_sp = live_valobj_sp; 1715 clang_expr_variable_sp->m_flags |= ClangExpressionVariable::EVIsProgramReference; 1716 break; 1717 } 1718 } 1719 else 1720 { 1721 // Make sure we aren't just trying to see the value of a persistent 1722 // variable (something like "$0") 1723 lldb::ClangExpressionVariableSP persistent_var_sp; 1724 // Only check for persistent variables the expression starts with a '$' 1725 if (expr_cstr[0] == '$') 1726 persistent_var_sp = m_persistent_variables.GetVariable (expr_cstr); 1727 1728 if (persistent_var_sp) 1729 { 1730 result_valobj_sp = persistent_var_sp->GetValueObject (); 1731 execution_results = eExecutionCompleted; 1732 } 1733 else 1734 { 1735 const char *prefix = GetExpressionPrefixContentsAsCString(); 1736 1737 execution_results = ClangUserExpression::Evaluate (exe_ctx, 1738 execution_policy, 1739 lldb::eLanguageTypeUnknown, 1740 coerce_to_id ? ClangUserExpression::eResultTypeId : ClangUserExpression::eResultTypeAny, 1741 unwind_on_error, 1742 expr_cstr, 1743 prefix, 1744 result_valobj_sp, 1745 single_thread_timeout_usec); 1746 } 1747 } 1748 1749 m_suppress_stop_hooks = old_suppress_value; 1750 1751 return execution_results; 1752 } 1753 1754 lldb::addr_t 1755 Target::GetCallableLoadAddress (lldb::addr_t load_addr, AddressClass addr_class) const 1756 { 1757 addr_t code_addr = load_addr; 1758 switch (m_arch.GetMachine()) 1759 { 1760 case llvm::Triple::arm: 1761 case llvm::Triple::thumb: 1762 switch (addr_class) 1763 { 1764 case eAddressClassData: 1765 case eAddressClassDebug: 1766 return LLDB_INVALID_ADDRESS; 1767 1768 case eAddressClassUnknown: 1769 case eAddressClassInvalid: 1770 case eAddressClassCode: 1771 case eAddressClassCodeAlternateISA: 1772 case eAddressClassRuntime: 1773 // Check if bit zero it no set? 1774 if ((code_addr & 1ull) == 0) 1775 { 1776 // Bit zero isn't set, check if the address is a multiple of 2? 1777 if (code_addr & 2ull) 1778 { 1779 // The address is a multiple of 2 so it must be thumb, set bit zero 1780 code_addr |= 1ull; 1781 } 1782 else if (addr_class == eAddressClassCodeAlternateISA) 1783 { 1784 // We checked the address and the address claims to be the alternate ISA 1785 // which means thumb, so set bit zero. 1786 code_addr |= 1ull; 1787 } 1788 } 1789 break; 1790 } 1791 break; 1792 1793 default: 1794 break; 1795 } 1796 return code_addr; 1797 } 1798 1799 lldb::addr_t 1800 Target::GetOpcodeLoadAddress (lldb::addr_t load_addr, AddressClass addr_class) const 1801 { 1802 addr_t opcode_addr = load_addr; 1803 switch (m_arch.GetMachine()) 1804 { 1805 case llvm::Triple::arm: 1806 case llvm::Triple::thumb: 1807 switch (addr_class) 1808 { 1809 case eAddressClassData: 1810 case eAddressClassDebug: 1811 return LLDB_INVALID_ADDRESS; 1812 1813 case eAddressClassInvalid: 1814 case eAddressClassUnknown: 1815 case eAddressClassCode: 1816 case eAddressClassCodeAlternateISA: 1817 case eAddressClassRuntime: 1818 opcode_addr &= ~(1ull); 1819 break; 1820 } 1821 break; 1822 1823 default: 1824 break; 1825 } 1826 return opcode_addr; 1827 } 1828 1829 lldb::user_id_t 1830 Target::AddStopHook (Target::StopHookSP &new_hook_sp) 1831 { 1832 lldb::user_id_t new_uid = ++m_stop_hook_next_id; 1833 new_hook_sp.reset (new StopHook(shared_from_this(), new_uid)); 1834 m_stop_hooks[new_uid] = new_hook_sp; 1835 return new_uid; 1836 } 1837 1838 bool 1839 Target::RemoveStopHookByID (lldb::user_id_t user_id) 1840 { 1841 size_t num_removed; 1842 num_removed = m_stop_hooks.erase (user_id); 1843 if (num_removed == 0) 1844 return false; 1845 else 1846 return true; 1847 } 1848 1849 void 1850 Target::RemoveAllStopHooks () 1851 { 1852 m_stop_hooks.clear(); 1853 } 1854 1855 Target::StopHookSP 1856 Target::GetStopHookByID (lldb::user_id_t user_id) 1857 { 1858 StopHookSP found_hook; 1859 1860 StopHookCollection::iterator specified_hook_iter; 1861 specified_hook_iter = m_stop_hooks.find (user_id); 1862 if (specified_hook_iter != m_stop_hooks.end()) 1863 found_hook = (*specified_hook_iter).second; 1864 return found_hook; 1865 } 1866 1867 bool 1868 Target::SetStopHookActiveStateByID (lldb::user_id_t user_id, bool active_state) 1869 { 1870 StopHookCollection::iterator specified_hook_iter; 1871 specified_hook_iter = m_stop_hooks.find (user_id); 1872 if (specified_hook_iter == m_stop_hooks.end()) 1873 return false; 1874 1875 (*specified_hook_iter).second->SetIsActive (active_state); 1876 return true; 1877 } 1878 1879 void 1880 Target::SetAllStopHooksActiveState (bool active_state) 1881 { 1882 StopHookCollection::iterator pos, end = m_stop_hooks.end(); 1883 for (pos = m_stop_hooks.begin(); pos != end; pos++) 1884 { 1885 (*pos).second->SetIsActive (active_state); 1886 } 1887 } 1888 1889 void 1890 Target::RunStopHooks () 1891 { 1892 if (m_suppress_stop_hooks) 1893 return; 1894 1895 if (!m_process_sp) 1896 return; 1897 1898 // <rdar://problem/12027563> make sure we check that we are not stopped because of us running a user expression 1899 // since in that case we do not want to run the stop-hooks 1900 if (m_process_sp->GetModIDRef().IsLastResumeForUserExpression()) 1901 return; 1902 1903 if (m_stop_hooks.empty()) 1904 return; 1905 1906 StopHookCollection::iterator pos, end = m_stop_hooks.end(); 1907 1908 // If there aren't any active stop hooks, don't bother either: 1909 bool any_active_hooks = false; 1910 for (pos = m_stop_hooks.begin(); pos != end; pos++) 1911 { 1912 if ((*pos).second->IsActive()) 1913 { 1914 any_active_hooks = true; 1915 break; 1916 } 1917 } 1918 if (!any_active_hooks) 1919 return; 1920 1921 CommandReturnObject result; 1922 1923 std::vector<ExecutionContext> exc_ctx_with_reasons; 1924 std::vector<SymbolContext> sym_ctx_with_reasons; 1925 1926 ThreadList &cur_threadlist = m_process_sp->GetThreadList(); 1927 size_t num_threads = cur_threadlist.GetSize(); 1928 for (size_t i = 0; i < num_threads; i++) 1929 { 1930 lldb::ThreadSP cur_thread_sp = cur_threadlist.GetThreadAtIndex (i); 1931 if (cur_thread_sp->ThreadStoppedForAReason()) 1932 { 1933 lldb::StackFrameSP cur_frame_sp = cur_thread_sp->GetStackFrameAtIndex(0); 1934 exc_ctx_with_reasons.push_back(ExecutionContext(m_process_sp.get(), cur_thread_sp.get(), cur_frame_sp.get())); 1935 sym_ctx_with_reasons.push_back(cur_frame_sp->GetSymbolContext(eSymbolContextEverything)); 1936 } 1937 } 1938 1939 // If no threads stopped for a reason, don't run the stop-hooks. 1940 size_t num_exe_ctx = exc_ctx_with_reasons.size(); 1941 if (num_exe_ctx == 0) 1942 return; 1943 1944 result.SetImmediateOutputStream (m_debugger.GetAsyncOutputStream()); 1945 result.SetImmediateErrorStream (m_debugger.GetAsyncErrorStream()); 1946 1947 bool keep_going = true; 1948 bool hooks_ran = false; 1949 bool print_hook_header; 1950 bool print_thread_header; 1951 1952 if (num_exe_ctx == 1) 1953 print_thread_header = false; 1954 else 1955 print_thread_header = true; 1956 1957 if (m_stop_hooks.size() == 1) 1958 print_hook_header = false; 1959 else 1960 print_hook_header = true; 1961 1962 for (pos = m_stop_hooks.begin(); keep_going && pos != end; pos++) 1963 { 1964 // result.Clear(); 1965 StopHookSP cur_hook_sp = (*pos).second; 1966 if (!cur_hook_sp->IsActive()) 1967 continue; 1968 1969 bool any_thread_matched = false; 1970 for (size_t i = 0; keep_going && i < num_exe_ctx; i++) 1971 { 1972 if ((cur_hook_sp->GetSpecifier () == NULL 1973 || cur_hook_sp->GetSpecifier()->SymbolContextMatches(sym_ctx_with_reasons[i])) 1974 && (cur_hook_sp->GetThreadSpecifier() == NULL 1975 || cur_hook_sp->GetThreadSpecifier()->ThreadPassesBasicTests(exc_ctx_with_reasons[i].GetThreadRef()))) 1976 { 1977 if (!hooks_ran) 1978 { 1979 hooks_ran = true; 1980 } 1981 if (print_hook_header && !any_thread_matched) 1982 { 1983 const char *cmd = (cur_hook_sp->GetCommands().GetSize() == 1 ? 1984 cur_hook_sp->GetCommands().GetStringAtIndex(0) : 1985 NULL); 1986 if (cmd) 1987 result.AppendMessageWithFormat("\n- Hook %llu (%s)\n", cur_hook_sp->GetID(), cmd); 1988 else 1989 result.AppendMessageWithFormat("\n- Hook %llu\n", cur_hook_sp->GetID()); 1990 any_thread_matched = true; 1991 } 1992 1993 if (print_thread_header) 1994 result.AppendMessageWithFormat("-- Thread %d\n", exc_ctx_with_reasons[i].GetThreadPtr()->GetIndexID()); 1995 1996 bool stop_on_continue = true; 1997 bool stop_on_error = true; 1998 bool echo_commands = false; 1999 bool print_results = true; 2000 GetDebugger().GetCommandInterpreter().HandleCommands (cur_hook_sp->GetCommands(), 2001 &exc_ctx_with_reasons[i], 2002 stop_on_continue, 2003 stop_on_error, 2004 echo_commands, 2005 print_results, 2006 eLazyBoolNo, 2007 result); 2008 2009 // If the command started the target going again, we should bag out of 2010 // running the stop hooks. 2011 if ((result.GetStatus() == eReturnStatusSuccessContinuingNoResult) || 2012 (result.GetStatus() == eReturnStatusSuccessContinuingResult)) 2013 { 2014 result.AppendMessageWithFormat ("Aborting stop hooks, hook %llu set the program running.", cur_hook_sp->GetID()); 2015 keep_going = false; 2016 } 2017 } 2018 } 2019 } 2020 2021 result.GetImmediateOutputStream()->Flush(); 2022 result.GetImmediateErrorStream()->Flush(); 2023 } 2024 2025 2026 //-------------------------------------------------------------- 2027 // class Target::StopHook 2028 //-------------------------------------------------------------- 2029 2030 2031 Target::StopHook::StopHook (lldb::TargetSP target_sp, lldb::user_id_t uid) : 2032 UserID (uid), 2033 m_target_sp (target_sp), 2034 m_commands (), 2035 m_specifier_sp (), 2036 m_thread_spec_ap(NULL), 2037 m_active (true) 2038 { 2039 } 2040 2041 Target::StopHook::StopHook (const StopHook &rhs) : 2042 UserID (rhs.GetID()), 2043 m_target_sp (rhs.m_target_sp), 2044 m_commands (rhs.m_commands), 2045 m_specifier_sp (rhs.m_specifier_sp), 2046 m_thread_spec_ap (NULL), 2047 m_active (rhs.m_active) 2048 { 2049 if (rhs.m_thread_spec_ap.get() != NULL) 2050 m_thread_spec_ap.reset (new ThreadSpec(*rhs.m_thread_spec_ap.get())); 2051 } 2052 2053 2054 Target::StopHook::~StopHook () 2055 { 2056 } 2057 2058 void 2059 Target::StopHook::SetThreadSpecifier (ThreadSpec *specifier) 2060 { 2061 m_thread_spec_ap.reset (specifier); 2062 } 2063 2064 2065 void 2066 Target::StopHook::GetDescription (Stream *s, lldb::DescriptionLevel level) const 2067 { 2068 int indent_level = s->GetIndentLevel(); 2069 2070 s->SetIndentLevel(indent_level + 2); 2071 2072 s->Printf ("Hook: %llu\n", GetID()); 2073 if (m_active) 2074 s->Indent ("State: enabled\n"); 2075 else 2076 s->Indent ("State: disabled\n"); 2077 2078 if (m_specifier_sp) 2079 { 2080 s->Indent(); 2081 s->PutCString ("Specifier:\n"); 2082 s->SetIndentLevel (indent_level + 4); 2083 m_specifier_sp->GetDescription (s, level); 2084 s->SetIndentLevel (indent_level + 2); 2085 } 2086 2087 if (m_thread_spec_ap.get() != NULL) 2088 { 2089 StreamString tmp; 2090 s->Indent("Thread:\n"); 2091 m_thread_spec_ap->GetDescription (&tmp, level); 2092 s->SetIndentLevel (indent_level + 4); 2093 s->Indent (tmp.GetData()); 2094 s->PutCString ("\n"); 2095 s->SetIndentLevel (indent_level + 2); 2096 } 2097 2098 s->Indent ("Commands: \n"); 2099 s->SetIndentLevel (indent_level + 4); 2100 uint32_t num_commands = m_commands.GetSize(); 2101 for (uint32_t i = 0; i < num_commands; i++) 2102 { 2103 s->Indent(m_commands.GetStringAtIndex(i)); 2104 s->PutCString ("\n"); 2105 } 2106 s->SetIndentLevel (indent_level); 2107 } 2108 2109 //-------------------------------------------------------------- 2110 // class TargetProperties 2111 //-------------------------------------------------------------- 2112 2113 OptionEnumValueElement 2114 lldb_private::g_dynamic_value_types[] = 2115 { 2116 { eNoDynamicValues, "no-dynamic-values", "Don't calculate the dynamic type of values"}, 2117 { eDynamicCanRunTarget, "run-target", "Calculate the dynamic type of values even if you have to run the target."}, 2118 { eDynamicDontRunTarget, "no-run-target", "Calculate the dynamic type of values, but don't run the target."}, 2119 { 0, NULL, NULL } 2120 }; 2121 2122 static OptionEnumValueElement 2123 g_inline_breakpoint_enums[] = 2124 { 2125 { 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."}, 2126 { eInlineBreakpointsHeaders, "headers", "Only check for inline breakpoint locations when setting breakpoints in header files, but not when setting breakpoint in implementation source files (default)."}, 2127 { eInlineBreakpointsAlways, "always", "Always look for inline breakpoint locations when setting file and line breakpoints (slower but most accurate)."}, 2128 { 0, NULL, NULL } 2129 }; 2130 2131 static PropertyDefinition 2132 g_properties[] = 2133 { 2134 { "default-arch" , OptionValue::eTypeArch , true , 0 , NULL, NULL, "Default architecture to choose, when there's a choice." }, 2135 { "expr-prefix" , OptionValue::eTypeFileSpec , false, 0 , NULL, NULL, "Path to a file containing expressions to be prepended to all expressions." }, 2136 { "prefer-dynamic-value" , OptionValue::eTypeEnum , false, eNoDynamicValues , NULL, g_dynamic_value_types, "Should printed values be shown as their dynamic value." }, 2137 { "enable-synthetic-value" , OptionValue::eTypeBoolean , false, true , NULL, NULL, "Should synthetic values be used by default whenever available." }, 2138 { "skip-prologue" , OptionValue::eTypeBoolean , false, true , NULL, NULL, "Skip function prologues when setting breakpoints by name." }, 2139 { "source-map" , OptionValue::eTypePathMap , false, 0 , NULL, NULL, "Source path remappings used to track the change of location between a source file when built, and " 2140 "where it exists on the current system. It consists of an array of duples, the first element of each duple is " 2141 "some part (starting at the root) of the path to the file when it was built, " 2142 "and the second is where the remainder of the original build hierarchy is rooted on the local system. " 2143 "Each element of the array is checked in order and the first one that results in a match wins." }, 2144 { "exec-search-paths" , OptionValue::eTypeFileSpecList, false, 0 , NULL, NULL, "Executable search paths to use when locating executable files whose paths don't match the local file system." }, 2145 { "max-children-count" , OptionValue::eTypeSInt64 , false, 256 , NULL, NULL, "Maximum number of children to expand in any level of depth." }, 2146 { "max-string-summary-length" , OptionValue::eTypeSInt64 , false, 1024 , NULL, NULL, "Maximum number of characters to show when using %s in summary strings." }, 2147 { "breakpoints-use-platform-avoid-list", OptionValue::eTypeBoolean , false, true , NULL, NULL, "Consult the platform module avoid list when setting non-module specific breakpoints." }, 2148 { "run-args" , OptionValue::eTypeArgs , false, 0 , NULL, NULL, "A list containing all the arguments to be passed to the executable when it is run." }, 2149 { "env-vars" , OptionValue::eTypeDictionary, false, OptionValue::eTypeString , NULL, NULL, "A list of all the environment variables to be passed to the executable's environment, and their values." }, 2150 { "inherit-env" , OptionValue::eTypeBoolean , false, true , NULL, NULL, "Inherit the environment from the process that is running LLDB." }, 2151 { "input-path" , OptionValue::eTypeFileSpec , false, 0 , NULL, NULL, "The file/path to be used by the executable program for reading its standard input." }, 2152 { "output-path" , OptionValue::eTypeFileSpec , false, 0 , NULL, NULL, "The file/path to be used by the executable program for writing its standard output." }, 2153 { "error-path" , OptionValue::eTypeFileSpec , false, 0 , NULL, NULL, "The file/path to be used by the executable program for writing its standard error." }, 2154 { "disable-aslr" , OptionValue::eTypeBoolean , false, true , NULL, NULL, "Disable Address Space Layout Randomization (ASLR)" }, 2155 { "disable-stdio" , OptionValue::eTypeBoolean , false, false , NULL, NULL, "Disable stdin/stdout for process (e.g. for a GUI application)" }, 2156 { "inline-breakpoint-strategy" , OptionValue::eTypeEnum , false, eInlineBreakpointsHeaders , NULL, g_inline_breakpoint_enums, "The strategy to use when settings breakpoints by file and line. " 2157 "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. " 2158 "Usually this is limitted to breakpoint locations from inlined functions from header or other include files, or more accurately non-implementation source files. " 2159 "Sometimes code might #include implementation files and cause inlined breakpoint locations in inlined implementation files. " 2160 "Always checking for inlined breakpoint locations can be expensive (memory and time), so we try to minimize the " 2161 "times we look for inlined locations. This setting allows you to control exactly which strategy is used when settings " 2162 "file and line breakpoints." }, 2163 { NULL , OptionValue::eTypeInvalid , false, 0 , NULL, NULL, NULL } 2164 }; 2165 enum 2166 { 2167 ePropertyDefaultArch, 2168 ePropertyExprPrefix, 2169 ePropertyPreferDynamic, 2170 ePropertyEnableSynthetic, 2171 ePropertySkipPrologue, 2172 ePropertySourceMap, 2173 ePropertyExecutableSearchPaths, 2174 ePropertyMaxChildrenCount, 2175 ePropertyMaxSummaryLength, 2176 ePropertyBreakpointUseAvoidList, 2177 ePropertyRunArgs, 2178 ePropertyEnvVars, 2179 ePropertyInheritEnv, 2180 ePropertyInputPath, 2181 ePropertyOutputPath, 2182 ePropertyErrorPath, 2183 ePropertyDisableASLR, 2184 ePropertyDisableSTDIO, 2185 ePropertyInlineStrategy 2186 }; 2187 2188 2189 class TargetOptionValueProperties : public OptionValueProperties 2190 { 2191 public: 2192 TargetOptionValueProperties (const ConstString &name) : 2193 OptionValueProperties (name), 2194 m_target (NULL), 2195 m_got_host_env (false) 2196 { 2197 } 2198 2199 // This constructor is used when creating TargetOptionValueProperties when it 2200 // is part of a new lldb_private::Target instance. It will copy all current 2201 // global property values as needed 2202 TargetOptionValueProperties (Target *target, const TargetPropertiesSP &target_properties_sp) : 2203 OptionValueProperties(*target_properties_sp->GetValueProperties()), 2204 m_target (target), 2205 m_got_host_env (false) 2206 { 2207 } 2208 2209 virtual const Property * 2210 GetPropertyAtIndex (const ExecutionContext *exe_ctx, bool will_modify, uint32_t idx) const 2211 { 2212 // When gettings the value for a key from the target options, we will always 2213 // try and grab the setting from the current target if there is one. Else we just 2214 // use the one from this instance. 2215 if (idx == ePropertyEnvVars) 2216 GetHostEnvironmentIfNeeded (); 2217 2218 if (exe_ctx) 2219 { 2220 Target *target = exe_ctx->GetTargetPtr(); 2221 if (target) 2222 { 2223 TargetOptionValueProperties *target_properties = static_cast<TargetOptionValueProperties *>(target->GetValueProperties().get()); 2224 if (this != target_properties) 2225 return target_properties->ProtectedGetPropertyAtIndex (idx); 2226 } 2227 } 2228 return ProtectedGetPropertyAtIndex (idx); 2229 } 2230 protected: 2231 2232 void 2233 GetHostEnvironmentIfNeeded () const 2234 { 2235 if (!m_got_host_env) 2236 { 2237 if (m_target) 2238 { 2239 m_got_host_env = true; 2240 const uint32_t idx = ePropertyInheritEnv; 2241 if (GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0)) 2242 { 2243 PlatformSP platform_sp (m_target->GetPlatform()); 2244 if (platform_sp) 2245 { 2246 StringList env; 2247 if (platform_sp->GetEnvironment(env)) 2248 { 2249 OptionValueDictionary *env_dict = GetPropertyAtIndexAsOptionValueDictionary (NULL, ePropertyEnvVars); 2250 if (env_dict) 2251 { 2252 const bool can_replace = false; 2253 const size_t envc = env.GetSize(); 2254 for (size_t idx=0; idx<envc; idx++) 2255 { 2256 const char *env_entry = env.GetStringAtIndex (idx); 2257 if (env_entry) 2258 { 2259 const char *equal_pos = ::strchr(env_entry, '='); 2260 ConstString key; 2261 // It is ok to have environment variables with no values 2262 const char *value = NULL; 2263 if (equal_pos) 2264 { 2265 key.SetCStringWithLength(env_entry, equal_pos - env_entry); 2266 if (equal_pos[1]) 2267 value = equal_pos + 1; 2268 } 2269 else 2270 { 2271 key.SetCString(env_entry); 2272 } 2273 // Don't allow existing keys to be replaced with ones we get from the platform environment 2274 env_dict->SetValueForKey(key, OptionValueSP(new OptionValueString(value)), can_replace); 2275 } 2276 } 2277 } 2278 } 2279 } 2280 } 2281 } 2282 } 2283 } 2284 Target *m_target; 2285 mutable bool m_got_host_env; 2286 }; 2287 2288 TargetProperties::TargetProperties (Target *target) : 2289 Properties () 2290 { 2291 if (target) 2292 { 2293 m_collection_sp.reset (new TargetOptionValueProperties(target, Target::GetGlobalProperties())); 2294 } 2295 else 2296 { 2297 m_collection_sp.reset (new TargetOptionValueProperties(ConstString("target"))); 2298 m_collection_sp->Initialize(g_properties); 2299 m_collection_sp->AppendProperty(ConstString("process"), 2300 ConstString("Settings specify to processes."), 2301 true, 2302 Process::GetGlobalProperties()->GetValueProperties()); 2303 } 2304 } 2305 2306 TargetProperties::~TargetProperties () 2307 { 2308 } 2309 ArchSpec 2310 TargetProperties::GetDefaultArchitecture () const 2311 { 2312 OptionValueArch *value = m_collection_sp->GetPropertyAtIndexAsOptionValueArch (NULL, ePropertyDefaultArch); 2313 if (value) 2314 return value->GetCurrentValue(); 2315 return ArchSpec(); 2316 } 2317 2318 void 2319 TargetProperties::SetDefaultArchitecture (const ArchSpec& arch) 2320 { 2321 OptionValueArch *value = m_collection_sp->GetPropertyAtIndexAsOptionValueArch (NULL, ePropertyDefaultArch); 2322 if (value) 2323 return value->SetCurrentValue(arch, true); 2324 } 2325 2326 lldb::DynamicValueType 2327 TargetProperties::GetPreferDynamicValue() const 2328 { 2329 const uint32_t idx = ePropertyPreferDynamic; 2330 return (lldb::DynamicValueType)m_collection_sp->GetPropertyAtIndexAsEnumeration (NULL, idx, g_properties[idx].default_uint_value); 2331 } 2332 2333 bool 2334 TargetProperties::GetDisableASLR () const 2335 { 2336 const uint32_t idx = ePropertyDisableASLR; 2337 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0); 2338 } 2339 2340 void 2341 TargetProperties::SetDisableASLR (bool b) 2342 { 2343 const uint32_t idx = ePropertyDisableASLR; 2344 m_collection_sp->SetPropertyAtIndexAsBoolean (NULL, idx, b); 2345 } 2346 2347 bool 2348 TargetProperties::GetDisableSTDIO () const 2349 { 2350 const uint32_t idx = ePropertyDisableSTDIO; 2351 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0); 2352 } 2353 2354 void 2355 TargetProperties::SetDisableSTDIO (bool b) 2356 { 2357 const uint32_t idx = ePropertyDisableSTDIO; 2358 m_collection_sp->SetPropertyAtIndexAsBoolean (NULL, idx, b); 2359 } 2360 2361 InlineStrategy 2362 TargetProperties::GetInlineStrategy () const 2363 { 2364 const uint32_t idx = ePropertyInlineStrategy; 2365 return (InlineStrategy)m_collection_sp->GetPropertyAtIndexAsEnumeration (NULL, idx, g_properties[idx].default_uint_value); 2366 } 2367 2368 bool 2369 TargetProperties::GetRunArguments (Args &args) const 2370 { 2371 const uint32_t idx = ePropertyRunArgs; 2372 return m_collection_sp->GetPropertyAtIndexAsArgs (NULL, idx, args); 2373 } 2374 2375 void 2376 TargetProperties::SetRunArguments (const Args &args) 2377 { 2378 const uint32_t idx = ePropertyRunArgs; 2379 m_collection_sp->SetPropertyAtIndexFromArgs (NULL, idx, args); 2380 } 2381 2382 size_t 2383 TargetProperties::GetEnvironmentAsArgs (Args &env) const 2384 { 2385 const uint32_t idx = ePropertyEnvVars; 2386 return m_collection_sp->GetPropertyAtIndexAsArgs (NULL, idx, env); 2387 } 2388 2389 bool 2390 TargetProperties::GetSkipPrologue() const 2391 { 2392 const uint32_t idx = ePropertySkipPrologue; 2393 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0); 2394 } 2395 2396 PathMappingList & 2397 TargetProperties::GetSourcePathMap () const 2398 { 2399 const uint32_t idx = ePropertySourceMap; 2400 OptionValuePathMappings *option_value = m_collection_sp->GetPropertyAtIndexAsOptionValuePathMappings (NULL, false, idx); 2401 assert(option_value); 2402 return option_value->GetCurrentValue(); 2403 } 2404 2405 FileSpecList & 2406 TargetProperties::GetExecutableSearchPaths () 2407 { 2408 const uint32_t idx = ePropertyExecutableSearchPaths; 2409 OptionValueFileSpecList *option_value = m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList (NULL, false, idx); 2410 assert(option_value); 2411 return option_value->GetCurrentValue(); 2412 } 2413 2414 bool 2415 TargetProperties::GetEnableSyntheticValue () const 2416 { 2417 const uint32_t idx = ePropertyEnableSynthetic; 2418 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0); 2419 } 2420 2421 uint32_t 2422 TargetProperties::GetMaximumNumberOfChildrenToDisplay() const 2423 { 2424 const uint32_t idx = ePropertyMaxChildrenCount; 2425 return m_collection_sp->GetPropertyAtIndexAsSInt64 (NULL, idx, g_properties[idx].default_uint_value); 2426 } 2427 2428 uint32_t 2429 TargetProperties::GetMaximumSizeOfStringSummary() const 2430 { 2431 const uint32_t idx = ePropertyMaxSummaryLength; 2432 return m_collection_sp->GetPropertyAtIndexAsSInt64 (NULL, idx, g_properties[idx].default_uint_value); 2433 } 2434 2435 FileSpec 2436 TargetProperties::GetStandardInputPath () const 2437 { 2438 const uint32_t idx = ePropertyInputPath; 2439 return m_collection_sp->GetPropertyAtIndexAsFileSpec (NULL, idx); 2440 } 2441 2442 void 2443 TargetProperties::SetStandardInputPath (const char *p) 2444 { 2445 const uint32_t idx = ePropertyInputPath; 2446 m_collection_sp->SetPropertyAtIndexAsString (NULL, idx, p); 2447 } 2448 2449 FileSpec 2450 TargetProperties::GetStandardOutputPath () const 2451 { 2452 const uint32_t idx = ePropertyOutputPath; 2453 return m_collection_sp->GetPropertyAtIndexAsFileSpec (NULL, idx); 2454 } 2455 2456 void 2457 TargetProperties::SetStandardOutputPath (const char *p) 2458 { 2459 const uint32_t idx = ePropertyOutputPath; 2460 m_collection_sp->SetPropertyAtIndexAsString (NULL, idx, p); 2461 } 2462 2463 FileSpec 2464 TargetProperties::GetStandardErrorPath () const 2465 { 2466 const uint32_t idx = ePropertyErrorPath; 2467 return m_collection_sp->GetPropertyAtIndexAsFileSpec(NULL, idx); 2468 } 2469 2470 const char * 2471 TargetProperties::GetExpressionPrefixContentsAsCString () 2472 { 2473 const uint32_t idx = ePropertyExprPrefix; 2474 OptionValueFileSpec *file = m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpec (NULL, false, idx); 2475 if (file) 2476 { 2477 const bool null_terminate = true; 2478 DataBufferSP data_sp(file->GetFileContents(null_terminate)); 2479 if (data_sp) 2480 return (const char *) data_sp->GetBytes(); 2481 } 2482 return NULL; 2483 } 2484 2485 void 2486 TargetProperties::SetStandardErrorPath (const char *p) 2487 { 2488 const uint32_t idx = ePropertyErrorPath; 2489 m_collection_sp->SetPropertyAtIndexAsString (NULL, idx, p); 2490 } 2491 2492 bool 2493 TargetProperties::GetBreakpointsConsultPlatformAvoidList () 2494 { 2495 const uint32_t idx = ePropertyBreakpointUseAvoidList; 2496 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0); 2497 } 2498 2499 const TargetPropertiesSP & 2500 Target::GetGlobalProperties() 2501 { 2502 static TargetPropertiesSP g_settings_sp; 2503 if (!g_settings_sp) 2504 { 2505 g_settings_sp.reset (new TargetProperties (NULL)); 2506 } 2507 return g_settings_sp; 2508 } 2509 2510 const ConstString & 2511 Target::TargetEventData::GetFlavorString () 2512 { 2513 static ConstString g_flavor ("Target::TargetEventData"); 2514 return g_flavor; 2515 } 2516 2517 const ConstString & 2518 Target::TargetEventData::GetFlavor () const 2519 { 2520 return TargetEventData::GetFlavorString (); 2521 } 2522 2523 Target::TargetEventData::TargetEventData (const lldb::TargetSP &new_target_sp) : 2524 EventData(), 2525 m_target_sp (new_target_sp) 2526 { 2527 } 2528 2529 Target::TargetEventData::~TargetEventData() 2530 { 2531 2532 } 2533 2534 void 2535 Target::TargetEventData::Dump (Stream *s) const 2536 { 2537 2538 } 2539 2540 const TargetSP 2541 Target::TargetEventData::GetTargetFromEvent (const lldb::EventSP &event_sp) 2542 { 2543 TargetSP target_sp; 2544 2545 const TargetEventData *data = GetEventDataFromEvent (event_sp.get()); 2546 if (data) 2547 target_sp = data->m_target_sp; 2548 2549 return target_sp; 2550 } 2551 2552 const Target::TargetEventData * 2553 Target::TargetEventData::GetEventDataFromEvent (const Event *event_ptr) 2554 { 2555 if (event_ptr) 2556 { 2557 const EventData *event_data = event_ptr->GetData(); 2558 if (event_data && event_data->GetFlavor() == TargetEventData::GetFlavorString()) 2559 return static_cast <const TargetEventData *> (event_ptr->GetData()); 2560 } 2561 return NULL; 2562 } 2563 2564