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/BreakpointResolverName.h" 20 #include "lldb/Core/Debugger.h" 21 #include "lldb/Core/Event.h" 22 #include "lldb/Core/Log.h" 23 #include "lldb/Core/StreamAsynchronousIO.h" 24 #include "lldb/Core/StreamString.h" 25 #include "lldb/Core/Timer.h" 26 #include "lldb/Core/ValueObject.h" 27 #include "lldb/Expression/ClangUserExpression.h" 28 #include "lldb/Host/Host.h" 29 #include "lldb/Interpreter/CommandInterpreter.h" 30 #include "lldb/Interpreter/CommandReturnObject.h" 31 #include "lldb/lldb-private-log.h" 32 #include "lldb/Symbol/ObjectFile.h" 33 #include "lldb/Target/Process.h" 34 #include "lldb/Target/StackFrame.h" 35 #include "lldb/Target/Thread.h" 36 #include "lldb/Target/ThreadSpec.h" 37 38 using namespace lldb; 39 using namespace lldb_private; 40 41 //---------------------------------------------------------------------- 42 // Target constructor 43 //---------------------------------------------------------------------- 44 Target::Target(Debugger &debugger, const ArchSpec &target_arch, const lldb::PlatformSP &platform_sp) : 45 Broadcaster ("lldb.target"), 46 ExecutionContextScope (), 47 TargetInstanceSettings (*GetSettingsController()), 48 m_debugger (debugger), 49 m_platform_sp (platform_sp), 50 m_mutex (Mutex::eMutexTypeRecursive), 51 m_arch (target_arch), 52 m_images (), 53 m_section_load_list (), 54 m_breakpoint_list (false), 55 m_internal_breakpoint_list (true), 56 m_watchpoint_location_list (), 57 m_process_sp (), 58 m_search_filter_sp (), 59 m_image_search_paths (ImageSearchPathsChanged, this), 60 m_scratch_ast_context_ap (NULL), 61 m_persistent_variables (), 62 m_source_manager(*this), 63 m_stop_hooks (), 64 m_stop_hook_next_id (0), 65 m_suppress_stop_hooks (false) 66 { 67 SetEventName (eBroadcastBitBreakpointChanged, "breakpoint-changed"); 68 SetEventName (eBroadcastBitModulesLoaded, "modules-loaded"); 69 SetEventName (eBroadcastBitModulesUnloaded, "modules-unloaded"); 70 71 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT)); 72 if (log) 73 log->Printf ("%p Target::Target()", this); 74 } 75 76 //---------------------------------------------------------------------- 77 // Destructor 78 //---------------------------------------------------------------------- 79 Target::~Target() 80 { 81 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT)); 82 if (log) 83 log->Printf ("%p Target::~Target()", this); 84 DeleteCurrentProcess (); 85 } 86 87 void 88 Target::Dump (Stream *s, lldb::DescriptionLevel description_level) 89 { 90 // s->Printf("%.*p: ", (int)sizeof(void*) * 2, this); 91 if (description_level != lldb::eDescriptionLevelBrief) 92 { 93 s->Indent(); 94 s->PutCString("Target\n"); 95 s->IndentMore(); 96 m_images.Dump(s); 97 m_breakpoint_list.Dump(s); 98 m_internal_breakpoint_list.Dump(s); 99 s->IndentLess(); 100 } 101 else 102 { 103 Module *exe_module = GetExecutableModulePointer(); 104 if (exe_module) 105 s->PutCString (exe_module->GetFileSpec().GetFilename().GetCString()); 106 else 107 s->PutCString ("No executable module."); 108 } 109 } 110 111 void 112 Target::DeleteCurrentProcess () 113 { 114 if (m_process_sp.get()) 115 { 116 m_section_load_list.Clear(); 117 if (m_process_sp->IsAlive()) 118 m_process_sp->Destroy(); 119 120 m_process_sp->Finalize(); 121 122 // Do any cleanup of the target we need to do between process instances. 123 // NB It is better to do this before destroying the process in case the 124 // clean up needs some help from the process. 125 m_breakpoint_list.ClearAllBreakpointSites(); 126 m_internal_breakpoint_list.ClearAllBreakpointSites(); 127 m_process_sp.reset(); 128 } 129 } 130 131 const lldb::ProcessSP & 132 Target::CreateProcess (Listener &listener, const char *plugin_name) 133 { 134 DeleteCurrentProcess (); 135 m_process_sp.reset(Process::FindPlugin(*this, plugin_name, listener)); 136 return m_process_sp; 137 } 138 139 const lldb::ProcessSP & 140 Target::GetProcessSP () const 141 { 142 return m_process_sp; 143 } 144 145 lldb::TargetSP 146 Target::GetSP() 147 { 148 return m_debugger.GetTargetList().GetTargetSP(this); 149 } 150 151 void 152 Target::Destroy() 153 { 154 Mutex::Locker locker (m_mutex); 155 DeleteCurrentProcess (); 156 m_platform_sp.reset(); 157 m_arch.Clear(); 158 m_images.Clear(); 159 m_section_load_list.Clear(); 160 const bool notify = false; 161 m_breakpoint_list.RemoveAll(notify); 162 m_internal_breakpoint_list.RemoveAll(notify); 163 m_last_created_breakpoint.reset(); 164 m_search_filter_sp.reset(); 165 m_image_search_paths.Clear(notify); 166 m_scratch_ast_context_ap.reset(); 167 m_persistent_variables.Clear(); 168 m_stop_hooks.clear(); 169 m_stop_hook_next_id = 0; 170 m_suppress_stop_hooks = false; 171 } 172 173 174 BreakpointList & 175 Target::GetBreakpointList(bool internal) 176 { 177 if (internal) 178 return m_internal_breakpoint_list; 179 else 180 return m_breakpoint_list; 181 } 182 183 const BreakpointList & 184 Target::GetBreakpointList(bool internal) const 185 { 186 if (internal) 187 return m_internal_breakpoint_list; 188 else 189 return m_breakpoint_list; 190 } 191 192 BreakpointSP 193 Target::GetBreakpointByID (break_id_t break_id) 194 { 195 BreakpointSP bp_sp; 196 197 if (LLDB_BREAK_ID_IS_INTERNAL (break_id)) 198 bp_sp = m_internal_breakpoint_list.FindBreakpointByID (break_id); 199 else 200 bp_sp = m_breakpoint_list.FindBreakpointByID (break_id); 201 202 return bp_sp; 203 } 204 205 BreakpointSP 206 Target::CreateBreakpoint (const FileSpec *containingModule, const FileSpec &file, uint32_t line_no, bool check_inlines, bool internal) 207 { 208 SearchFilterSP filter_sp(GetSearchFilterForModule (containingModule)); 209 BreakpointResolverSP resolver_sp(new BreakpointResolverFileLine (NULL, file, line_no, check_inlines)); 210 return CreateBreakpoint (filter_sp, resolver_sp, internal); 211 } 212 213 214 BreakpointSP 215 Target::CreateBreakpoint (lldb::addr_t addr, bool internal) 216 { 217 Address so_addr; 218 // Attempt to resolve our load address if possible, though it is ok if 219 // it doesn't resolve to section/offset. 220 221 // Try and resolve as a load address if possible 222 m_section_load_list.ResolveLoadAddress(addr, so_addr); 223 if (!so_addr.IsValid()) 224 { 225 // The address didn't resolve, so just set this as an absolute address 226 so_addr.SetOffset (addr); 227 } 228 BreakpointSP bp_sp (CreateBreakpoint(so_addr, internal)); 229 return bp_sp; 230 } 231 232 BreakpointSP 233 Target::CreateBreakpoint (Address &addr, bool internal) 234 { 235 TargetSP target_sp = this->GetSP(); 236 SearchFilterSP filter_sp(new SearchFilter (target_sp)); 237 BreakpointResolverSP resolver_sp (new BreakpointResolverAddress (NULL, addr)); 238 return CreateBreakpoint (filter_sp, resolver_sp, internal); 239 } 240 241 BreakpointSP 242 Target::CreateBreakpoint (const FileSpec *containingModule, 243 const char *func_name, 244 uint32_t func_name_type_mask, 245 bool internal, 246 LazyBool skip_prologue) 247 { 248 BreakpointSP bp_sp; 249 if (func_name) 250 { 251 SearchFilterSP filter_sp(GetSearchFilterForModule (containingModule)); 252 253 BreakpointResolverSP resolver_sp (new BreakpointResolverName (NULL, 254 func_name, 255 func_name_type_mask, 256 Breakpoint::Exact, 257 skip_prologue == eLazyBoolCalculate ? GetSkipPrologue() : skip_prologue)); 258 bp_sp = CreateBreakpoint (filter_sp, resolver_sp, internal); 259 } 260 return bp_sp; 261 } 262 263 264 SearchFilterSP 265 Target::GetSearchFilterForModule (const FileSpec *containingModule) 266 { 267 SearchFilterSP filter_sp; 268 lldb::TargetSP target_sp = this->GetSP(); 269 if (containingModule != NULL) 270 { 271 // TODO: We should look into sharing module based search filters 272 // across many breakpoints like we do for the simple target based one 273 filter_sp.reset (new SearchFilterByModule (target_sp, *containingModule)); 274 } 275 else 276 { 277 if (m_search_filter_sp.get() == NULL) 278 m_search_filter_sp.reset (new SearchFilter (target_sp)); 279 filter_sp = m_search_filter_sp; 280 } 281 return filter_sp; 282 } 283 284 BreakpointSP 285 Target::CreateBreakpoint (const FileSpec *containingModule, 286 RegularExpression &func_regex, 287 bool internal, 288 LazyBool skip_prologue) 289 { 290 SearchFilterSP filter_sp(GetSearchFilterForModule (containingModule)); 291 BreakpointResolverSP resolver_sp(new BreakpointResolverName (NULL, 292 func_regex, 293 skip_prologue == eLazyBoolCalculate ? GetSkipPrologue() : skip_prologue)); 294 295 return CreateBreakpoint (filter_sp, resolver_sp, internal); 296 } 297 298 BreakpointSP 299 Target::CreateBreakpoint (SearchFilterSP &filter_sp, BreakpointResolverSP &resolver_sp, bool internal) 300 { 301 BreakpointSP bp_sp; 302 if (filter_sp && resolver_sp) 303 { 304 bp_sp.reset(new Breakpoint (*this, filter_sp, resolver_sp)); 305 resolver_sp->SetBreakpoint (bp_sp.get()); 306 307 if (internal) 308 m_internal_breakpoint_list.Add (bp_sp, false); 309 else 310 m_breakpoint_list.Add (bp_sp, true); 311 312 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS)); 313 if (log) 314 { 315 StreamString s; 316 bp_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose); 317 log->Printf ("Target::%s (internal = %s) => break_id = %s\n", __FUNCTION__, internal ? "yes" : "no", s.GetData()); 318 } 319 320 bp_sp->ResolveBreakpoint(); 321 } 322 323 if (!internal && bp_sp) 324 { 325 m_last_created_breakpoint = bp_sp; 326 } 327 328 return bp_sp; 329 } 330 331 // See also WatchpointLocation::SetWatchpointType() and OptionGroupWatchpoint::WatchType. 332 WatchpointLocationSP 333 Target::CreateWatchpointLocation(lldb::addr_t addr, size_t size, uint32_t type) 334 { 335 WatchpointLocationSP wp_loc_sp; 336 bool process_is_valid = m_process_sp && m_process_sp->IsAlive(); 337 if (!process_is_valid) 338 return wp_loc_sp; 339 if (addr == LLDB_INVALID_ADDRESS) 340 return wp_loc_sp; 341 if (size == 0) 342 return wp_loc_sp; 343 344 // FIXME: Add implmenetation. 345 return wp_loc_sp; 346 } 347 348 void 349 Target::RemoveAllBreakpoints (bool internal_also) 350 { 351 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS)); 352 if (log) 353 log->Printf ("Target::%s (internal_also = %s)\n", __FUNCTION__, internal_also ? "yes" : "no"); 354 355 m_breakpoint_list.RemoveAll (true); 356 if (internal_also) 357 m_internal_breakpoint_list.RemoveAll (false); 358 359 m_last_created_breakpoint.reset(); 360 } 361 362 void 363 Target::DisableAllBreakpoints (bool internal_also) 364 { 365 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS)); 366 if (log) 367 log->Printf ("Target::%s (internal_also = %s)\n", __FUNCTION__, internal_also ? "yes" : "no"); 368 369 m_breakpoint_list.SetEnabledAll (false); 370 if (internal_also) 371 m_internal_breakpoint_list.SetEnabledAll (false); 372 } 373 374 void 375 Target::EnableAllBreakpoints (bool internal_also) 376 { 377 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS)); 378 if (log) 379 log->Printf ("Target::%s (internal_also = %s)\n", __FUNCTION__, internal_also ? "yes" : "no"); 380 381 m_breakpoint_list.SetEnabledAll (true); 382 if (internal_also) 383 m_internal_breakpoint_list.SetEnabledAll (true); 384 } 385 386 bool 387 Target::RemoveBreakpointByID (break_id_t break_id) 388 { 389 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS)); 390 if (log) 391 log->Printf ("Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__, break_id, LLDB_BREAK_ID_IS_INTERNAL (break_id) ? "yes" : "no"); 392 393 if (DisableBreakpointByID (break_id)) 394 { 395 if (LLDB_BREAK_ID_IS_INTERNAL (break_id)) 396 m_internal_breakpoint_list.Remove(break_id, false); 397 else 398 { 399 if (m_last_created_breakpoint) 400 { 401 if (m_last_created_breakpoint->GetID() == break_id) 402 m_last_created_breakpoint.reset(); 403 } 404 m_breakpoint_list.Remove(break_id, true); 405 } 406 return true; 407 } 408 return false; 409 } 410 411 bool 412 Target::DisableBreakpointByID (break_id_t break_id) 413 { 414 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS)); 415 if (log) 416 log->Printf ("Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__, break_id, LLDB_BREAK_ID_IS_INTERNAL (break_id) ? "yes" : "no"); 417 418 BreakpointSP bp_sp; 419 420 if (LLDB_BREAK_ID_IS_INTERNAL (break_id)) 421 bp_sp = m_internal_breakpoint_list.FindBreakpointByID (break_id); 422 else 423 bp_sp = m_breakpoint_list.FindBreakpointByID (break_id); 424 if (bp_sp) 425 { 426 bp_sp->SetEnabled (false); 427 return true; 428 } 429 return false; 430 } 431 432 bool 433 Target::EnableBreakpointByID (break_id_t break_id) 434 { 435 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS)); 436 if (log) 437 log->Printf ("Target::%s (break_id = %i, internal = %s)\n", 438 __FUNCTION__, 439 break_id, 440 LLDB_BREAK_ID_IS_INTERNAL (break_id) ? "yes" : "no"); 441 442 BreakpointSP bp_sp; 443 444 if (LLDB_BREAK_ID_IS_INTERNAL (break_id)) 445 bp_sp = m_internal_breakpoint_list.FindBreakpointByID (break_id); 446 else 447 bp_sp = m_breakpoint_list.FindBreakpointByID (break_id); 448 449 if (bp_sp) 450 { 451 bp_sp->SetEnabled (true); 452 return true; 453 } 454 return false; 455 } 456 457 ModuleSP 458 Target::GetExecutableModule () 459 { 460 return m_images.GetModuleAtIndex(0); 461 } 462 463 Module* 464 Target::GetExecutableModulePointer () 465 { 466 return m_images.GetModulePointerAtIndex(0); 467 } 468 469 void 470 Target::SetExecutableModule (ModuleSP& executable_sp, bool get_dependent_files) 471 { 472 m_images.Clear(); 473 m_scratch_ast_context_ap.reset(); 474 475 if (executable_sp.get()) 476 { 477 Timer scoped_timer (__PRETTY_FUNCTION__, 478 "Target::SetExecutableModule (executable = '%s/%s')", 479 executable_sp->GetFileSpec().GetDirectory().AsCString(), 480 executable_sp->GetFileSpec().GetFilename().AsCString()); 481 482 m_images.Append(executable_sp); // The first image is our exectuable file 483 484 // If we haven't set an architecture yet, reset our architecture based on what we found in the executable module. 485 if (!m_arch.IsValid()) 486 m_arch = executable_sp->GetArchitecture(); 487 488 FileSpecList dependent_files; 489 ObjectFile *executable_objfile = executable_sp->GetObjectFile(); 490 // Let's find the file & line for main and set the default source file from there. 491 if (!m_source_manager.DefaultFileAndLineSet()) 492 { 493 SymbolContextList sc_list; 494 uint32_t num_matches; 495 ConstString main_name("main"); 496 bool symbols_okay = false; // Force it to be a debug symbol. 497 bool append = false; 498 num_matches = executable_sp->FindFunctions (main_name, eFunctionNameTypeBase, symbols_okay, append, sc_list); 499 for (uint32_t idx = 0; idx < num_matches; idx++) 500 { 501 SymbolContext sc; 502 sc_list.GetContextAtIndex(idx, sc); 503 if (sc.line_entry.file) 504 { 505 m_source_manager.SetDefaultFileAndLine(sc.line_entry.file, sc.line_entry.line); 506 break; 507 } 508 } 509 } 510 511 if (executable_objfile) 512 { 513 executable_objfile->GetDependentModules(dependent_files); 514 for (uint32_t i=0; i<dependent_files.GetSize(); i++) 515 { 516 FileSpec dependent_file_spec (dependent_files.GetFileSpecPointerAtIndex(i)); 517 FileSpec platform_dependent_file_spec; 518 if (m_platform_sp) 519 m_platform_sp->GetFile (dependent_file_spec, NULL, platform_dependent_file_spec); 520 else 521 platform_dependent_file_spec = dependent_file_spec; 522 523 ModuleSP image_module_sp(GetSharedModule (platform_dependent_file_spec, 524 m_arch)); 525 if (image_module_sp.get()) 526 { 527 ObjectFile *objfile = image_module_sp->GetObjectFile(); 528 if (objfile) 529 objfile->GetDependentModules(dependent_files); 530 } 531 } 532 } 533 534 } 535 536 UpdateInstanceName(); 537 } 538 539 540 bool 541 Target::SetArchitecture (const ArchSpec &arch_spec) 542 { 543 if (m_arch == arch_spec) 544 { 545 // If we're setting the architecture to our current architecture, we 546 // don't need to do anything. 547 return true; 548 } 549 else if (!m_arch.IsValid()) 550 { 551 // If we haven't got a valid arch spec, then we just need to set it. 552 m_arch = arch_spec; 553 return true; 554 } 555 else 556 { 557 // If we have an executable file, try to reset the executable to the desired architecture 558 m_arch = arch_spec; 559 ModuleSP executable_sp = GetExecutableModule (); 560 m_images.Clear(); 561 m_scratch_ast_context_ap.reset(); 562 // Need to do something about unsetting breakpoints. 563 564 if (executable_sp) 565 { 566 FileSpec exec_file_spec = executable_sp->GetFileSpec(); 567 Error error = ModuleList::GetSharedModule(exec_file_spec, 568 arch_spec, 569 NULL, 570 NULL, 571 0, 572 executable_sp, 573 NULL, 574 NULL); 575 576 if (!error.Fail() && executable_sp) 577 { 578 SetExecutableModule (executable_sp, true); 579 return true; 580 } 581 else 582 { 583 return false; 584 } 585 } 586 else 587 { 588 return false; 589 } 590 } 591 } 592 593 void 594 Target::ModuleAdded (ModuleSP &module_sp) 595 { 596 // A module is being added to this target for the first time 597 ModuleList module_list; 598 module_list.Append(module_sp); 599 ModulesDidLoad (module_list); 600 } 601 602 void 603 Target::ModuleUpdated (ModuleSP &old_module_sp, ModuleSP &new_module_sp) 604 { 605 // A module is replacing an already added module 606 ModuleList module_list; 607 module_list.Append (old_module_sp); 608 ModulesDidUnload (module_list); 609 module_list.Clear (); 610 module_list.Append (new_module_sp); 611 ModulesDidLoad (module_list); 612 } 613 614 void 615 Target::ModulesDidLoad (ModuleList &module_list) 616 { 617 m_breakpoint_list.UpdateBreakpoints (module_list, true); 618 // TODO: make event data that packages up the module_list 619 BroadcastEvent (eBroadcastBitModulesLoaded, NULL); 620 } 621 622 void 623 Target::ModulesDidUnload (ModuleList &module_list) 624 { 625 m_breakpoint_list.UpdateBreakpoints (module_list, false); 626 627 // Remove the images from the target image list 628 m_images.Remove(module_list); 629 630 // TODO: make event data that packages up the module_list 631 BroadcastEvent (eBroadcastBitModulesUnloaded, NULL); 632 } 633 634 size_t 635 Target::ReadMemoryFromFileCache (const Address& addr, void *dst, size_t dst_len, Error &error) 636 { 637 const Section *section = addr.GetSection(); 638 if (section && section->GetModule()) 639 { 640 ObjectFile *objfile = section->GetModule()->GetObjectFile(); 641 if (objfile) 642 { 643 size_t bytes_read = section->ReadSectionDataFromObjectFile (objfile, 644 addr.GetOffset(), 645 dst, 646 dst_len); 647 if (bytes_read > 0) 648 return bytes_read; 649 else 650 error.SetErrorStringWithFormat("error reading data from section %s", section->GetName().GetCString()); 651 } 652 else 653 { 654 error.SetErrorString("address isn't from a object file"); 655 } 656 } 657 else 658 { 659 error.SetErrorString("address doesn't contain a section that points to a section in a object file"); 660 } 661 return 0; 662 } 663 664 size_t 665 Target::ReadMemory (const Address& addr, 666 bool prefer_file_cache, 667 void *dst, 668 size_t dst_len, 669 Error &error, 670 lldb::addr_t *load_addr_ptr) 671 { 672 error.Clear(); 673 674 // if we end up reading this from process memory, we will fill this 675 // with the actual load address 676 if (load_addr_ptr) 677 *load_addr_ptr = LLDB_INVALID_ADDRESS; 678 679 bool process_is_valid = m_process_sp && m_process_sp->IsAlive(); 680 681 size_t bytes_read = 0; 682 683 addr_t load_addr = LLDB_INVALID_ADDRESS; 684 addr_t file_addr = LLDB_INVALID_ADDRESS; 685 Address resolved_addr; 686 if (!addr.IsSectionOffset()) 687 { 688 if (m_section_load_list.IsEmpty()) 689 { 690 // No sections are loaded, so we must assume we are not running 691 // yet and anything we are given is a file address. 692 file_addr = addr.GetOffset(); // "addr" doesn't have a section, so its offset is the file address 693 m_images.ResolveFileAddress (file_addr, resolved_addr); 694 } 695 else 696 { 697 // We have at least one section loaded. This can be becuase 698 // we have manually loaded some sections with "target modules load ..." 699 // or because we have have a live process that has sections loaded 700 // through the dynamic loader 701 load_addr = addr.GetOffset(); // "addr" doesn't have a section, so its offset is the load address 702 m_section_load_list.ResolveLoadAddress (load_addr, resolved_addr); 703 } 704 } 705 if (!resolved_addr.IsValid()) 706 resolved_addr = addr; 707 708 709 if (prefer_file_cache) 710 { 711 bytes_read = ReadMemoryFromFileCache (resolved_addr, dst, dst_len, error); 712 if (bytes_read > 0) 713 return bytes_read; 714 } 715 716 if (process_is_valid) 717 { 718 if (load_addr == LLDB_INVALID_ADDRESS) 719 load_addr = resolved_addr.GetLoadAddress (this); 720 721 if (load_addr == LLDB_INVALID_ADDRESS) 722 { 723 if (resolved_addr.GetModule() && resolved_addr.GetModule()->GetFileSpec()) 724 error.SetErrorStringWithFormat("%s[0x%llx] can't be resolved, %s in not currently loaded.\n", 725 resolved_addr.GetModule()->GetFileSpec().GetFilename().AsCString(), 726 resolved_addr.GetFileAddress()); 727 else 728 error.SetErrorStringWithFormat("0x%llx can't be resolved.\n", resolved_addr.GetFileAddress()); 729 } 730 else 731 { 732 bytes_read = m_process_sp->ReadMemory(load_addr, dst, dst_len, error); 733 if (bytes_read != dst_len) 734 { 735 if (error.Success()) 736 { 737 if (bytes_read == 0) 738 error.SetErrorStringWithFormat("Read memory from 0x%llx failed.\n", load_addr); 739 else 740 error.SetErrorStringWithFormat("Only %zu of %zu bytes were read from memory at 0x%llx.\n", bytes_read, dst_len, load_addr); 741 } 742 } 743 if (bytes_read) 744 { 745 if (load_addr_ptr) 746 *load_addr_ptr = load_addr; 747 return bytes_read; 748 } 749 // If the address is not section offset we have an address that 750 // doesn't resolve to any address in any currently loaded shared 751 // libaries and we failed to read memory so there isn't anything 752 // more we can do. If it is section offset, we might be able to 753 // read cached memory from the object file. 754 if (!resolved_addr.IsSectionOffset()) 755 return 0; 756 } 757 } 758 759 if (!prefer_file_cache && resolved_addr.IsSectionOffset()) 760 { 761 // If we didn't already try and read from the object file cache, then 762 // try it after failing to read from the process. 763 return ReadMemoryFromFileCache (resolved_addr, dst, dst_len, error); 764 } 765 return 0; 766 } 767 768 size_t 769 Target::ReadScalarIntegerFromMemory (const Address& addr, 770 bool prefer_file_cache, 771 uint32_t byte_size, 772 bool is_signed, 773 Scalar &scalar, 774 Error &error) 775 { 776 uint64_t uval; 777 778 if (byte_size <= sizeof(uval)) 779 { 780 size_t bytes_read = ReadMemory (addr, prefer_file_cache, &uval, byte_size, error); 781 if (bytes_read == byte_size) 782 { 783 DataExtractor data (&uval, sizeof(uval), m_arch.GetByteOrder(), m_arch.GetAddressByteSize()); 784 uint32_t offset = 0; 785 if (byte_size <= 4) 786 scalar = data.GetMaxU32 (&offset, byte_size); 787 else 788 scalar = data.GetMaxU64 (&offset, byte_size); 789 790 if (is_signed) 791 scalar.SignExtend(byte_size * 8); 792 return bytes_read; 793 } 794 } 795 else 796 { 797 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size); 798 } 799 return 0; 800 } 801 802 uint64_t 803 Target::ReadUnsignedIntegerFromMemory (const Address& addr, 804 bool prefer_file_cache, 805 size_t integer_byte_size, 806 uint64_t fail_value, 807 Error &error) 808 { 809 Scalar scalar; 810 if (ReadScalarIntegerFromMemory (addr, 811 prefer_file_cache, 812 integer_byte_size, 813 false, 814 scalar, 815 error)) 816 return scalar.ULongLong(fail_value); 817 return fail_value; 818 } 819 820 bool 821 Target::ReadPointerFromMemory (const Address& addr, 822 bool prefer_file_cache, 823 Error &error, 824 Address &pointer_addr) 825 { 826 Scalar scalar; 827 if (ReadScalarIntegerFromMemory (addr, 828 prefer_file_cache, 829 m_arch.GetAddressByteSize(), 830 false, 831 scalar, 832 error)) 833 { 834 addr_t pointer_vm_addr = scalar.ULongLong(LLDB_INVALID_ADDRESS); 835 if (pointer_vm_addr != LLDB_INVALID_ADDRESS) 836 { 837 if (m_section_load_list.IsEmpty()) 838 { 839 // No sections are loaded, so we must assume we are not running 840 // yet and anything we are given is a file address. 841 m_images.ResolveFileAddress (pointer_vm_addr, pointer_addr); 842 } 843 else 844 { 845 // We have at least one section loaded. This can be becuase 846 // we have manually loaded some sections with "target modules load ..." 847 // or because we have have a live process that has sections loaded 848 // through the dynamic loader 849 m_section_load_list.ResolveLoadAddress (pointer_vm_addr, pointer_addr); 850 } 851 // We weren't able to resolve the pointer value, so just return 852 // an address with no section 853 if (!pointer_addr.IsValid()) 854 pointer_addr.SetOffset (pointer_vm_addr); 855 return true; 856 857 } 858 } 859 return false; 860 } 861 862 ModuleSP 863 Target::GetSharedModule 864 ( 865 const FileSpec& file_spec, 866 const ArchSpec& arch, 867 const lldb_private::UUID *uuid_ptr, 868 const ConstString *object_name, 869 off_t object_offset, 870 Error *error_ptr 871 ) 872 { 873 // Don't pass in the UUID so we can tell if we have a stale value in our list 874 ModuleSP old_module_sp; // This will get filled in if we have a new version of the library 875 bool did_create_module = false; 876 ModuleSP module_sp; 877 878 Error error; 879 880 // If there are image search path entries, try to use them first to acquire a suitable image. 881 if (m_image_search_paths.GetSize()) 882 { 883 FileSpec transformed_spec; 884 if (m_image_search_paths.RemapPath (file_spec.GetDirectory(), transformed_spec.GetDirectory())) 885 { 886 transformed_spec.GetFilename() = file_spec.GetFilename(); 887 error = ModuleList::GetSharedModule (transformed_spec, arch, uuid_ptr, object_name, object_offset, module_sp, &old_module_sp, &did_create_module); 888 } 889 } 890 891 // The platform is responsible for finding and caching an appropriate 892 // module in the shared module cache. 893 if (m_platform_sp) 894 { 895 FileSpec platform_file_spec; 896 error = m_platform_sp->GetSharedModule (file_spec, 897 arch, 898 uuid_ptr, 899 object_name, 900 object_offset, 901 module_sp, 902 &old_module_sp, 903 &did_create_module); 904 } 905 else 906 { 907 error.SetErrorString("no platform is currently set"); 908 } 909 910 // If a module hasn't been found yet, use the unmodified path. 911 if (module_sp) 912 { 913 m_images.Append (module_sp); 914 if (did_create_module) 915 { 916 if (old_module_sp && m_images.GetIndexForModule (old_module_sp.get()) != LLDB_INVALID_INDEX32) 917 ModuleUpdated(old_module_sp, module_sp); 918 else 919 ModuleAdded(module_sp); 920 } 921 } 922 if (error_ptr) 923 *error_ptr = error; 924 return module_sp; 925 } 926 927 928 Target * 929 Target::CalculateTarget () 930 { 931 return this; 932 } 933 934 Process * 935 Target::CalculateProcess () 936 { 937 return NULL; 938 } 939 940 Thread * 941 Target::CalculateThread () 942 { 943 return NULL; 944 } 945 946 StackFrame * 947 Target::CalculateStackFrame () 948 { 949 return NULL; 950 } 951 952 void 953 Target::CalculateExecutionContext (ExecutionContext &exe_ctx) 954 { 955 exe_ctx.target = this; 956 exe_ctx.process = NULL; // Do NOT fill in process... 957 exe_ctx.thread = NULL; 958 exe_ctx.frame = NULL; 959 } 960 961 PathMappingList & 962 Target::GetImageSearchPathList () 963 { 964 return m_image_search_paths; 965 } 966 967 void 968 Target::ImageSearchPathsChanged 969 ( 970 const PathMappingList &path_list, 971 void *baton 972 ) 973 { 974 Target *target = (Target *)baton; 975 ModuleSP exe_module_sp (target->GetExecutableModule()); 976 if (exe_module_sp) 977 { 978 target->m_images.Clear(); 979 target->SetExecutableModule (exe_module_sp, true); 980 } 981 } 982 983 ClangASTContext * 984 Target::GetScratchClangASTContext() 985 { 986 // Now see if we know the target triple, and if so, create our scratch AST context: 987 if (m_scratch_ast_context_ap.get() == NULL && m_arch.IsValid()) 988 m_scratch_ast_context_ap.reset (new ClangASTContext(m_arch.GetTriple().str().c_str())); 989 return m_scratch_ast_context_ap.get(); 990 } 991 992 void 993 Target::SettingsInitialize () 994 { 995 UserSettingsControllerSP &usc = GetSettingsController(); 996 usc.reset (new SettingsController); 997 UserSettingsController::InitializeSettingsController (usc, 998 SettingsController::global_settings_table, 999 SettingsController::instance_settings_table); 1000 1001 // Now call SettingsInitialize() on each 'child' setting of Target 1002 Process::SettingsInitialize (); 1003 } 1004 1005 void 1006 Target::SettingsTerminate () 1007 { 1008 1009 // Must call SettingsTerminate() on each settings 'child' of Target, before terminating Target's Settings. 1010 1011 Process::SettingsTerminate (); 1012 1013 // Now terminate Target Settings. 1014 1015 UserSettingsControllerSP &usc = GetSettingsController(); 1016 UserSettingsController::FinalizeSettingsController (usc); 1017 usc.reset(); 1018 } 1019 1020 UserSettingsControllerSP & 1021 Target::GetSettingsController () 1022 { 1023 static UserSettingsControllerSP g_settings_controller; 1024 return g_settings_controller; 1025 } 1026 1027 ArchSpec 1028 Target::GetDefaultArchitecture () 1029 { 1030 lldb::UserSettingsControllerSP settings_controller_sp (GetSettingsController()); 1031 1032 if (settings_controller_sp) 1033 return static_cast<Target::SettingsController *>(settings_controller_sp.get())->GetArchitecture (); 1034 return ArchSpec(); 1035 } 1036 1037 void 1038 Target::SetDefaultArchitecture (const ArchSpec& arch) 1039 { 1040 lldb::UserSettingsControllerSP settings_controller_sp (GetSettingsController()); 1041 1042 if (settings_controller_sp) 1043 static_cast<Target::SettingsController *>(settings_controller_sp.get())->GetArchitecture () = arch; 1044 } 1045 1046 Target * 1047 Target::GetTargetFromContexts (const ExecutionContext *exe_ctx_ptr, const SymbolContext *sc_ptr) 1048 { 1049 // The target can either exist in the "process" of ExecutionContext, or in 1050 // the "target_sp" member of SymbolContext. This accessor helper function 1051 // will get the target from one of these locations. 1052 1053 Target *target = NULL; 1054 if (sc_ptr != NULL) 1055 target = sc_ptr->target_sp.get(); 1056 if (target == NULL) 1057 { 1058 if (exe_ctx_ptr != NULL && exe_ctx_ptr->process != NULL) 1059 target = &exe_ctx_ptr->process->GetTarget(); 1060 } 1061 return target; 1062 } 1063 1064 1065 void 1066 Target::UpdateInstanceName () 1067 { 1068 StreamString sstr; 1069 1070 Module *exe_module = GetExecutableModulePointer(); 1071 if (exe_module) 1072 { 1073 sstr.Printf ("%s_%s", 1074 exe_module->GetFileSpec().GetFilename().AsCString(), 1075 exe_module->GetArchitecture().GetArchitectureName()); 1076 GetSettingsController()->RenameInstanceSettings (GetInstanceName().AsCString(), sstr.GetData()); 1077 } 1078 } 1079 1080 const char * 1081 Target::GetExpressionPrefixContentsAsCString () 1082 { 1083 if (m_expr_prefix_contents_sp) 1084 return (const char *)m_expr_prefix_contents_sp->GetBytes(); 1085 return NULL; 1086 } 1087 1088 ExecutionResults 1089 Target::EvaluateExpression 1090 ( 1091 const char *expr_cstr, 1092 StackFrame *frame, 1093 bool unwind_on_error, 1094 bool keep_in_memory, 1095 lldb::DynamicValueType use_dynamic, 1096 lldb::ValueObjectSP &result_valobj_sp 1097 ) 1098 { 1099 ExecutionResults execution_results = eExecutionSetupError; 1100 1101 result_valobj_sp.reset(); 1102 1103 // We shouldn't run stop hooks in expressions. 1104 // Be sure to reset this if you return anywhere within this function. 1105 bool old_suppress_value = m_suppress_stop_hooks; 1106 m_suppress_stop_hooks = true; 1107 1108 ExecutionContext exe_ctx; 1109 if (frame) 1110 { 1111 frame->CalculateExecutionContext(exe_ctx); 1112 Error error; 1113 const uint32_t expr_path_options = StackFrame::eExpressionPathOptionCheckPtrVsMember | 1114 StackFrame::eExpressionPathOptionsNoFragileObjcIvar | 1115 StackFrame::eExpressionPathOptionsNoSyntheticChildren; 1116 lldb::VariableSP var_sp; 1117 result_valobj_sp = frame->GetValueForVariableExpressionPath (expr_cstr, 1118 use_dynamic, 1119 expr_path_options, 1120 var_sp, 1121 error); 1122 } 1123 else if (m_process_sp) 1124 { 1125 m_process_sp->CalculateExecutionContext(exe_ctx); 1126 } 1127 else 1128 { 1129 CalculateExecutionContext(exe_ctx); 1130 } 1131 1132 if (result_valobj_sp) 1133 { 1134 execution_results = eExecutionCompleted; 1135 // We got a result from the frame variable expression path above... 1136 ConstString persistent_variable_name (m_persistent_variables.GetNextPersistentVariableName()); 1137 1138 lldb::ValueObjectSP const_valobj_sp; 1139 1140 // Check in case our value is already a constant value 1141 if (result_valobj_sp->GetIsConstant()) 1142 { 1143 const_valobj_sp = result_valobj_sp; 1144 const_valobj_sp->SetName (persistent_variable_name); 1145 } 1146 else 1147 { 1148 if (use_dynamic != lldb::eNoDynamicValues) 1149 { 1150 ValueObjectSP dynamic_sp = result_valobj_sp->GetDynamicValue(use_dynamic); 1151 if (dynamic_sp) 1152 result_valobj_sp = dynamic_sp; 1153 } 1154 1155 const_valobj_sp = result_valobj_sp->CreateConstantValue (persistent_variable_name); 1156 } 1157 1158 lldb::ValueObjectSP live_valobj_sp = result_valobj_sp; 1159 1160 result_valobj_sp = const_valobj_sp; 1161 1162 ClangExpressionVariableSP clang_expr_variable_sp(m_persistent_variables.CreatePersistentVariable(result_valobj_sp)); 1163 assert (clang_expr_variable_sp.get()); 1164 1165 // Set flags and live data as appropriate 1166 1167 const Value &result_value = live_valobj_sp->GetValue(); 1168 1169 switch (result_value.GetValueType()) 1170 { 1171 case Value::eValueTypeHostAddress: 1172 case Value::eValueTypeFileAddress: 1173 // we don't do anything with these for now 1174 break; 1175 case Value::eValueTypeScalar: 1176 clang_expr_variable_sp->m_flags |= ClangExpressionVariable::EVIsLLDBAllocated; 1177 clang_expr_variable_sp->m_flags |= ClangExpressionVariable::EVNeedsAllocation; 1178 break; 1179 case Value::eValueTypeLoadAddress: 1180 clang_expr_variable_sp->m_live_sp = live_valobj_sp; 1181 clang_expr_variable_sp->m_flags |= ClangExpressionVariable::EVIsProgramReference; 1182 break; 1183 } 1184 } 1185 else 1186 { 1187 // Make sure we aren't just trying to see the value of a persistent 1188 // variable (something like "$0") 1189 lldb::ClangExpressionVariableSP persistent_var_sp; 1190 // Only check for persistent variables the expression starts with a '$' 1191 if (expr_cstr[0] == '$') 1192 persistent_var_sp = m_persistent_variables.GetVariable (expr_cstr); 1193 1194 if (persistent_var_sp) 1195 { 1196 result_valobj_sp = persistent_var_sp->GetValueObject (); 1197 execution_results = eExecutionCompleted; 1198 } 1199 else 1200 { 1201 const char *prefix = GetExpressionPrefixContentsAsCString(); 1202 1203 execution_results = ClangUserExpression::Evaluate (exe_ctx, 1204 unwind_on_error, 1205 expr_cstr, 1206 prefix, 1207 result_valobj_sp); 1208 } 1209 } 1210 1211 m_suppress_stop_hooks = old_suppress_value; 1212 1213 return execution_results; 1214 } 1215 1216 lldb::addr_t 1217 Target::GetCallableLoadAddress (lldb::addr_t load_addr, AddressClass addr_class) const 1218 { 1219 addr_t code_addr = load_addr; 1220 switch (m_arch.GetMachine()) 1221 { 1222 case llvm::Triple::arm: 1223 case llvm::Triple::thumb: 1224 switch (addr_class) 1225 { 1226 case eAddressClassData: 1227 case eAddressClassDebug: 1228 return LLDB_INVALID_ADDRESS; 1229 1230 case eAddressClassUnknown: 1231 case eAddressClassInvalid: 1232 case eAddressClassCode: 1233 case eAddressClassCodeAlternateISA: 1234 case eAddressClassRuntime: 1235 // Check if bit zero it no set? 1236 if ((code_addr & 1ull) == 0) 1237 { 1238 // Bit zero isn't set, check if the address is a multiple of 2? 1239 if (code_addr & 2ull) 1240 { 1241 // The address is a multiple of 2 so it must be thumb, set bit zero 1242 code_addr |= 1ull; 1243 } 1244 else if (addr_class == eAddressClassCodeAlternateISA) 1245 { 1246 // We checked the address and the address claims to be the alternate ISA 1247 // which means thumb, so set bit zero. 1248 code_addr |= 1ull; 1249 } 1250 } 1251 break; 1252 } 1253 break; 1254 1255 default: 1256 break; 1257 } 1258 return code_addr; 1259 } 1260 1261 lldb::addr_t 1262 Target::GetOpcodeLoadAddress (lldb::addr_t load_addr, AddressClass addr_class) const 1263 { 1264 addr_t opcode_addr = load_addr; 1265 switch (m_arch.GetMachine()) 1266 { 1267 case llvm::Triple::arm: 1268 case llvm::Triple::thumb: 1269 switch (addr_class) 1270 { 1271 case eAddressClassData: 1272 case eAddressClassDebug: 1273 return LLDB_INVALID_ADDRESS; 1274 1275 case eAddressClassInvalid: 1276 case eAddressClassUnknown: 1277 case eAddressClassCode: 1278 case eAddressClassCodeAlternateISA: 1279 case eAddressClassRuntime: 1280 opcode_addr &= ~(1ull); 1281 break; 1282 } 1283 break; 1284 1285 default: 1286 break; 1287 } 1288 return opcode_addr; 1289 } 1290 1291 lldb::user_id_t 1292 Target::AddStopHook (Target::StopHookSP &new_hook_sp) 1293 { 1294 lldb::user_id_t new_uid = ++m_stop_hook_next_id; 1295 new_hook_sp.reset (new StopHook(GetSP(), new_uid)); 1296 m_stop_hooks[new_uid] = new_hook_sp; 1297 return new_uid; 1298 } 1299 1300 bool 1301 Target::RemoveStopHookByID (lldb::user_id_t user_id) 1302 { 1303 size_t num_removed; 1304 num_removed = m_stop_hooks.erase (user_id); 1305 if (num_removed == 0) 1306 return false; 1307 else 1308 return true; 1309 } 1310 1311 void 1312 Target::RemoveAllStopHooks () 1313 { 1314 m_stop_hooks.clear(); 1315 } 1316 1317 Target::StopHookSP 1318 Target::GetStopHookByID (lldb::user_id_t user_id) 1319 { 1320 StopHookSP found_hook; 1321 1322 StopHookCollection::iterator specified_hook_iter; 1323 specified_hook_iter = m_stop_hooks.find (user_id); 1324 if (specified_hook_iter != m_stop_hooks.end()) 1325 found_hook = (*specified_hook_iter).second; 1326 return found_hook; 1327 } 1328 1329 bool 1330 Target::SetStopHookActiveStateByID (lldb::user_id_t user_id, bool active_state) 1331 { 1332 StopHookCollection::iterator specified_hook_iter; 1333 specified_hook_iter = m_stop_hooks.find (user_id); 1334 if (specified_hook_iter == m_stop_hooks.end()) 1335 return false; 1336 1337 (*specified_hook_iter).second->SetIsActive (active_state); 1338 return true; 1339 } 1340 1341 void 1342 Target::SetAllStopHooksActiveState (bool active_state) 1343 { 1344 StopHookCollection::iterator pos, end = m_stop_hooks.end(); 1345 for (pos = m_stop_hooks.begin(); pos != end; pos++) 1346 { 1347 (*pos).second->SetIsActive (active_state); 1348 } 1349 } 1350 1351 void 1352 Target::RunStopHooks () 1353 { 1354 if (m_suppress_stop_hooks) 1355 return; 1356 1357 if (!m_process_sp) 1358 return; 1359 1360 if (m_stop_hooks.empty()) 1361 return; 1362 1363 StopHookCollection::iterator pos, end = m_stop_hooks.end(); 1364 1365 // If there aren't any active stop hooks, don't bother either: 1366 bool any_active_hooks = false; 1367 for (pos = m_stop_hooks.begin(); pos != end; pos++) 1368 { 1369 if ((*pos).second->IsActive()) 1370 { 1371 any_active_hooks = true; 1372 break; 1373 } 1374 } 1375 if (!any_active_hooks) 1376 return; 1377 1378 CommandReturnObject result; 1379 1380 std::vector<ExecutionContext> exc_ctx_with_reasons; 1381 std::vector<SymbolContext> sym_ctx_with_reasons; 1382 1383 ThreadList &cur_threadlist = m_process_sp->GetThreadList(); 1384 size_t num_threads = cur_threadlist.GetSize(); 1385 for (size_t i = 0; i < num_threads; i++) 1386 { 1387 lldb::ThreadSP cur_thread_sp = cur_threadlist.GetThreadAtIndex (i); 1388 if (cur_thread_sp->ThreadStoppedForAReason()) 1389 { 1390 lldb::StackFrameSP cur_frame_sp = cur_thread_sp->GetStackFrameAtIndex(0); 1391 exc_ctx_with_reasons.push_back(ExecutionContext(m_process_sp.get(), cur_thread_sp.get(), cur_frame_sp.get())); 1392 sym_ctx_with_reasons.push_back(cur_frame_sp->GetSymbolContext(eSymbolContextEverything)); 1393 } 1394 } 1395 1396 // If no threads stopped for a reason, don't run the stop-hooks. 1397 size_t num_exe_ctx = exc_ctx_with_reasons.size(); 1398 if (num_exe_ctx == 0) 1399 return; 1400 1401 result.SetImmediateOutputStream (m_debugger.GetAsyncOutputStream()); 1402 result.SetImmediateErrorStream (m_debugger.GetAsyncErrorStream()); 1403 1404 bool keep_going = true; 1405 bool hooks_ran = false; 1406 bool print_hook_header; 1407 bool print_thread_header; 1408 1409 if (num_exe_ctx == 1) 1410 print_thread_header = false; 1411 else 1412 print_thread_header = true; 1413 1414 if (m_stop_hooks.size() == 1) 1415 print_hook_header = false; 1416 else 1417 print_hook_header = true; 1418 1419 for (pos = m_stop_hooks.begin(); keep_going && pos != end; pos++) 1420 { 1421 // result.Clear(); 1422 StopHookSP cur_hook_sp = (*pos).second; 1423 if (!cur_hook_sp->IsActive()) 1424 continue; 1425 1426 bool any_thread_matched = false; 1427 for (size_t i = 0; keep_going && i < num_exe_ctx; i++) 1428 { 1429 if ((cur_hook_sp->GetSpecifier () == NULL 1430 || cur_hook_sp->GetSpecifier()->SymbolContextMatches(sym_ctx_with_reasons[i])) 1431 && (cur_hook_sp->GetThreadSpecifier() == NULL 1432 || cur_hook_sp->GetThreadSpecifier()->ThreadPassesBasicTests(exc_ctx_with_reasons[i].thread))) 1433 { 1434 if (!hooks_ran) 1435 { 1436 result.AppendMessage("\n** Stop Hooks **"); 1437 hooks_ran = true; 1438 } 1439 if (print_hook_header && !any_thread_matched) 1440 { 1441 result.AppendMessageWithFormat("\n- Hook %d\n", cur_hook_sp->GetID()); 1442 any_thread_matched = true; 1443 } 1444 1445 if (print_thread_header) 1446 result.AppendMessageWithFormat("-- Thread %d\n", exc_ctx_with_reasons[i].thread->GetIndexID()); 1447 1448 bool stop_on_continue = true; 1449 bool stop_on_error = true; 1450 bool echo_commands = false; 1451 bool print_results = true; 1452 GetDebugger().GetCommandInterpreter().HandleCommands (cur_hook_sp->GetCommands(), 1453 &exc_ctx_with_reasons[i], 1454 stop_on_continue, 1455 stop_on_error, 1456 echo_commands, 1457 print_results, 1458 result); 1459 1460 // If the command started the target going again, we should bag out of 1461 // running the stop hooks. 1462 if ((result.GetStatus() == eReturnStatusSuccessContinuingNoResult) || 1463 (result.GetStatus() == eReturnStatusSuccessContinuingResult)) 1464 { 1465 result.AppendMessageWithFormat ("Aborting stop hooks, hook %d set the program running.", cur_hook_sp->GetID()); 1466 keep_going = false; 1467 } 1468 } 1469 } 1470 } 1471 if (hooks_ran) 1472 result.AppendMessage ("\n** End Stop Hooks **\n"); 1473 1474 result.GetImmediateOutputStream()->Flush(); 1475 result.GetImmediateErrorStream()->Flush(); 1476 } 1477 1478 bool 1479 Target::LoadModuleWithSlide (Module *module, lldb::addr_t slide) 1480 { 1481 bool changed = false; 1482 if (module) 1483 { 1484 ObjectFile *object_file = module->GetObjectFile(); 1485 if (object_file) 1486 { 1487 SectionList *section_list = object_file->GetSectionList (); 1488 if (section_list) 1489 { 1490 // All sections listed in the dyld image info structure will all 1491 // either be fixed up already, or they will all be off by a single 1492 // slide amount that is determined by finding the first segment 1493 // that is at file offset zero which also has bytes (a file size 1494 // that is greater than zero) in the object file. 1495 1496 // Determine the slide amount (if any) 1497 const size_t num_sections = section_list->GetSize(); 1498 size_t sect_idx = 0; 1499 for (sect_idx = 0; sect_idx < num_sections; ++sect_idx) 1500 { 1501 // Iterate through the object file sections to find the 1502 // first section that starts of file offset zero and that 1503 // has bytes in the file... 1504 Section *section = section_list->GetSectionAtIndex (sect_idx).get(); 1505 if (section) 1506 { 1507 if (m_section_load_list.SetSectionLoadAddress (section, section->GetFileAddress() + slide)) 1508 changed = true; 1509 } 1510 } 1511 } 1512 } 1513 } 1514 return changed; 1515 } 1516 1517 1518 //-------------------------------------------------------------- 1519 // class Target::StopHook 1520 //-------------------------------------------------------------- 1521 1522 1523 Target::StopHook::StopHook (lldb::TargetSP target_sp, lldb::user_id_t uid) : 1524 UserID (uid), 1525 m_target_sp (target_sp), 1526 m_commands (), 1527 m_specifier_sp (), 1528 m_thread_spec_ap(NULL), 1529 m_active (true) 1530 { 1531 } 1532 1533 Target::StopHook::StopHook (const StopHook &rhs) : 1534 UserID (rhs.GetID()), 1535 m_target_sp (rhs.m_target_sp), 1536 m_commands (rhs.m_commands), 1537 m_specifier_sp (rhs.m_specifier_sp), 1538 m_thread_spec_ap (NULL), 1539 m_active (rhs.m_active) 1540 { 1541 if (rhs.m_thread_spec_ap.get() != NULL) 1542 m_thread_spec_ap.reset (new ThreadSpec(*rhs.m_thread_spec_ap.get())); 1543 } 1544 1545 1546 Target::StopHook::~StopHook () 1547 { 1548 } 1549 1550 void 1551 Target::StopHook::SetThreadSpecifier (ThreadSpec *specifier) 1552 { 1553 m_thread_spec_ap.reset (specifier); 1554 } 1555 1556 1557 void 1558 Target::StopHook::GetDescription (Stream *s, lldb::DescriptionLevel level) const 1559 { 1560 int indent_level = s->GetIndentLevel(); 1561 1562 s->SetIndentLevel(indent_level + 2); 1563 1564 s->Printf ("Hook: %d\n", GetID()); 1565 if (m_active) 1566 s->Indent ("State: enabled\n"); 1567 else 1568 s->Indent ("State: disabled\n"); 1569 1570 if (m_specifier_sp) 1571 { 1572 s->Indent(); 1573 s->PutCString ("Specifier:\n"); 1574 s->SetIndentLevel (indent_level + 4); 1575 m_specifier_sp->GetDescription (s, level); 1576 s->SetIndentLevel (indent_level + 2); 1577 } 1578 1579 if (m_thread_spec_ap.get() != NULL) 1580 { 1581 StreamString tmp; 1582 s->Indent("Thread:\n"); 1583 m_thread_spec_ap->GetDescription (&tmp, level); 1584 s->SetIndentLevel (indent_level + 4); 1585 s->Indent (tmp.GetData()); 1586 s->PutCString ("\n"); 1587 s->SetIndentLevel (indent_level + 2); 1588 } 1589 1590 s->Indent ("Commands: \n"); 1591 s->SetIndentLevel (indent_level + 4); 1592 uint32_t num_commands = m_commands.GetSize(); 1593 for (uint32_t i = 0; i < num_commands; i++) 1594 { 1595 s->Indent(m_commands.GetStringAtIndex(i)); 1596 s->PutCString ("\n"); 1597 } 1598 s->SetIndentLevel (indent_level); 1599 } 1600 1601 1602 //-------------------------------------------------------------- 1603 // class Target::SettingsController 1604 //-------------------------------------------------------------- 1605 1606 Target::SettingsController::SettingsController () : 1607 UserSettingsController ("target", Debugger::GetSettingsController()), 1608 m_default_architecture () 1609 { 1610 m_default_settings.reset (new TargetInstanceSettings (*this, false, 1611 InstanceSettings::GetDefaultName().AsCString())); 1612 } 1613 1614 Target::SettingsController::~SettingsController () 1615 { 1616 } 1617 1618 lldb::InstanceSettingsSP 1619 Target::SettingsController::CreateInstanceSettings (const char *instance_name) 1620 { 1621 TargetInstanceSettings *new_settings = new TargetInstanceSettings (*GetSettingsController(), 1622 false, 1623 instance_name); 1624 lldb::InstanceSettingsSP new_settings_sp (new_settings); 1625 return new_settings_sp; 1626 } 1627 1628 1629 #define TSC_DEFAULT_ARCH "default-arch" 1630 #define TSC_EXPR_PREFIX "expr-prefix" 1631 #define TSC_PREFER_DYNAMIC "prefer-dynamic-value" 1632 #define TSC_SKIP_PROLOGUE "skip-prologue" 1633 #define TSC_SOURCE_MAP "source-map" 1634 #define TSC_MAX_CHILDREN "max-children-count" 1635 #define TSC_MAX_STRLENSUMMARY "max-string-summary-length" 1636 1637 1638 static const ConstString & 1639 GetSettingNameForDefaultArch () 1640 { 1641 static ConstString g_const_string (TSC_DEFAULT_ARCH); 1642 return g_const_string; 1643 } 1644 1645 static const ConstString & 1646 GetSettingNameForExpressionPrefix () 1647 { 1648 static ConstString g_const_string (TSC_EXPR_PREFIX); 1649 return g_const_string; 1650 } 1651 1652 static const ConstString & 1653 GetSettingNameForPreferDynamicValue () 1654 { 1655 static ConstString g_const_string (TSC_PREFER_DYNAMIC); 1656 return g_const_string; 1657 } 1658 1659 static const ConstString & 1660 GetSettingNameForSourcePathMap () 1661 { 1662 static ConstString g_const_string (TSC_SOURCE_MAP); 1663 return g_const_string; 1664 } 1665 1666 static const ConstString & 1667 GetSettingNameForSkipPrologue () 1668 { 1669 static ConstString g_const_string (TSC_SKIP_PROLOGUE); 1670 return g_const_string; 1671 } 1672 1673 static const ConstString & 1674 GetSettingNameForMaxChildren () 1675 { 1676 static ConstString g_const_string (TSC_MAX_CHILDREN); 1677 return g_const_string; 1678 } 1679 1680 static const ConstString & 1681 GetSettingNameForMaxStringSummaryLength () 1682 { 1683 static ConstString g_const_string (TSC_MAX_STRLENSUMMARY); 1684 return g_const_string; 1685 } 1686 1687 bool 1688 Target::SettingsController::SetGlobalVariable (const ConstString &var_name, 1689 const char *index_value, 1690 const char *value, 1691 const SettingEntry &entry, 1692 const VarSetOperationType op, 1693 Error&err) 1694 { 1695 if (var_name == GetSettingNameForDefaultArch()) 1696 { 1697 m_default_architecture.SetTriple (value, NULL); 1698 if (!m_default_architecture.IsValid()) 1699 err.SetErrorStringWithFormat ("'%s' is not a valid architecture or triple.", value); 1700 } 1701 return true; 1702 } 1703 1704 1705 bool 1706 Target::SettingsController::GetGlobalVariable (const ConstString &var_name, 1707 StringList &value, 1708 Error &err) 1709 { 1710 if (var_name == GetSettingNameForDefaultArch()) 1711 { 1712 // If the arch is invalid (the default), don't show a string for it 1713 if (m_default_architecture.IsValid()) 1714 value.AppendString (m_default_architecture.GetArchitectureName()); 1715 return true; 1716 } 1717 else 1718 err.SetErrorStringWithFormat ("unrecognized variable name '%s'", var_name.AsCString()); 1719 1720 return false; 1721 } 1722 1723 //-------------------------------------------------------------- 1724 // class TargetInstanceSettings 1725 //-------------------------------------------------------------- 1726 1727 TargetInstanceSettings::TargetInstanceSettings 1728 ( 1729 UserSettingsController &owner, 1730 bool live_instance, 1731 const char *name 1732 ) : 1733 InstanceSettings (owner, name ? name : InstanceSettings::InvalidName().AsCString(), live_instance), 1734 m_expr_prefix_file (), 1735 m_expr_prefix_contents_sp (), 1736 m_prefer_dynamic_value (2), 1737 m_skip_prologue (true, true), 1738 m_source_map (NULL, NULL), 1739 m_max_children_display(256), 1740 m_max_strlen_length(1024) 1741 { 1742 // CopyInstanceSettings is a pure virtual function in InstanceSettings; it therefore cannot be called 1743 // until the vtables for TargetInstanceSettings are properly set up, i.e. AFTER all the initializers. 1744 // For this reason it has to be called here, rather than in the initializer or in the parent constructor. 1745 // This is true for CreateInstanceName() too. 1746 1747 if (GetInstanceName () == InstanceSettings::InvalidName()) 1748 { 1749 ChangeInstanceName (std::string (CreateInstanceName().AsCString())); 1750 m_owner.RegisterInstanceSettings (this); 1751 } 1752 1753 if (live_instance) 1754 { 1755 const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name); 1756 CopyInstanceSettings (pending_settings,false); 1757 } 1758 } 1759 1760 TargetInstanceSettings::TargetInstanceSettings (const TargetInstanceSettings &rhs) : 1761 InstanceSettings (*Target::GetSettingsController(), CreateInstanceName().AsCString()), 1762 m_expr_prefix_file (rhs.m_expr_prefix_file), 1763 m_expr_prefix_contents_sp (rhs.m_expr_prefix_contents_sp), 1764 m_prefer_dynamic_value (rhs.m_prefer_dynamic_value), 1765 m_skip_prologue (rhs.m_skip_prologue), 1766 m_source_map (rhs.m_source_map), 1767 m_max_children_display(rhs.m_max_children_display), 1768 m_max_strlen_length(rhs.m_max_strlen_length) 1769 { 1770 if (m_instance_name != InstanceSettings::GetDefaultName()) 1771 { 1772 const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name); 1773 CopyInstanceSettings (pending_settings,false); 1774 } 1775 } 1776 1777 TargetInstanceSettings::~TargetInstanceSettings () 1778 { 1779 } 1780 1781 TargetInstanceSettings& 1782 TargetInstanceSettings::operator= (const TargetInstanceSettings &rhs) 1783 { 1784 if (this != &rhs) 1785 { 1786 } 1787 1788 return *this; 1789 } 1790 1791 void 1792 TargetInstanceSettings::UpdateInstanceSettingsVariable (const ConstString &var_name, 1793 const char *index_value, 1794 const char *value, 1795 const ConstString &instance_name, 1796 const SettingEntry &entry, 1797 VarSetOperationType op, 1798 Error &err, 1799 bool pending) 1800 { 1801 if (var_name == GetSettingNameForExpressionPrefix ()) 1802 { 1803 err = UserSettingsController::UpdateFileSpecOptionValue (value, op, m_expr_prefix_file); 1804 if (err.Success()) 1805 { 1806 switch (op) 1807 { 1808 default: 1809 break; 1810 case eVarSetOperationAssign: 1811 case eVarSetOperationAppend: 1812 { 1813 if (!m_expr_prefix_file.GetCurrentValue().Exists()) 1814 { 1815 err.SetErrorToGenericError (); 1816 err.SetErrorStringWithFormat ("%s does not exist.\n", value); 1817 return; 1818 } 1819 1820 m_expr_prefix_contents_sp = m_expr_prefix_file.GetCurrentValue().ReadFileContents(); 1821 1822 if (!m_expr_prefix_contents_sp && m_expr_prefix_contents_sp->GetByteSize() == 0) 1823 { 1824 err.SetErrorStringWithFormat ("Couldn't read data from '%s'\n", value); 1825 m_expr_prefix_contents_sp.reset(); 1826 } 1827 } 1828 break; 1829 case eVarSetOperationClear: 1830 m_expr_prefix_contents_sp.reset(); 1831 } 1832 } 1833 } 1834 else if (var_name == GetSettingNameForPreferDynamicValue()) 1835 { 1836 int new_value; 1837 UserSettingsController::UpdateEnumVariable (g_dynamic_value_types, &new_value, value, err); 1838 if (err.Success()) 1839 m_prefer_dynamic_value = new_value; 1840 } 1841 else if (var_name == GetSettingNameForSkipPrologue()) 1842 { 1843 err = UserSettingsController::UpdateBooleanOptionValue (value, op, m_skip_prologue); 1844 } 1845 else if (var_name == GetSettingNameForMaxChildren()) 1846 { 1847 bool ok; 1848 uint32_t new_value = Args::StringToUInt32(value, 0, 10, &ok); 1849 if (ok) 1850 m_max_children_display = new_value; 1851 } 1852 else if (var_name == GetSettingNameForMaxStringSummaryLength()) 1853 { 1854 bool ok; 1855 uint32_t new_value = Args::StringToUInt32(value, 0, 10, &ok); 1856 if (ok) 1857 m_max_strlen_length = new_value; 1858 } 1859 else if (var_name == GetSettingNameForSourcePathMap ()) 1860 { 1861 switch (op) 1862 { 1863 case eVarSetOperationReplace: 1864 case eVarSetOperationInsertBefore: 1865 case eVarSetOperationInsertAfter: 1866 case eVarSetOperationRemove: 1867 default: 1868 break; 1869 case eVarSetOperationAssign: 1870 m_source_map.Clear(true); 1871 // Fall through to append.... 1872 case eVarSetOperationAppend: 1873 { 1874 Args args(value); 1875 const uint32_t argc = args.GetArgumentCount(); 1876 if (argc & 1 || argc == 0) 1877 { 1878 err.SetErrorStringWithFormat ("an even number of paths must be supplied to to the source-map setting: %u arguments given", argc); 1879 } 1880 else 1881 { 1882 char resolved_new_path[PATH_MAX]; 1883 FileSpec file_spec; 1884 const char *old_path; 1885 for (uint32_t idx = 0; (old_path = args.GetArgumentAtIndex(idx)) != NULL; idx += 2) 1886 { 1887 const char *new_path = args.GetArgumentAtIndex(idx+1); 1888 assert (new_path); // We have an even number of paths, this shouldn't happen! 1889 1890 file_spec.SetFile(new_path, true); 1891 if (file_spec.Exists()) 1892 { 1893 if (file_spec.GetPath (resolved_new_path, sizeof(resolved_new_path)) >= sizeof(resolved_new_path)) 1894 { 1895 err.SetErrorStringWithFormat("new path '%s' is too long", new_path); 1896 return; 1897 } 1898 } 1899 else 1900 { 1901 err.SetErrorStringWithFormat("new path '%s' doesn't exist", new_path); 1902 return; 1903 } 1904 m_source_map.Append(ConstString (old_path), ConstString (resolved_new_path), true); 1905 } 1906 } 1907 } 1908 break; 1909 1910 case eVarSetOperationClear: 1911 m_source_map.Clear(true); 1912 break; 1913 } 1914 } 1915 } 1916 1917 void 1918 TargetInstanceSettings::CopyInstanceSettings (const lldb::InstanceSettingsSP &new_settings, bool pending) 1919 { 1920 TargetInstanceSettings *new_settings_ptr = static_cast <TargetInstanceSettings *> (new_settings.get()); 1921 1922 if (!new_settings_ptr) 1923 return; 1924 1925 m_expr_prefix_file = new_settings_ptr->m_expr_prefix_file; 1926 m_expr_prefix_contents_sp = new_settings_ptr->m_expr_prefix_contents_sp; 1927 m_prefer_dynamic_value = new_settings_ptr->m_prefer_dynamic_value; 1928 m_skip_prologue = new_settings_ptr->m_skip_prologue; 1929 m_max_children_display = new_settings_ptr->m_max_children_display; 1930 m_max_strlen_length = new_settings_ptr->m_max_strlen_length; 1931 } 1932 1933 bool 1934 TargetInstanceSettings::GetInstanceSettingsValue (const SettingEntry &entry, 1935 const ConstString &var_name, 1936 StringList &value, 1937 Error *err) 1938 { 1939 if (var_name == GetSettingNameForExpressionPrefix ()) 1940 { 1941 char path[PATH_MAX]; 1942 const size_t path_len = m_expr_prefix_file.GetCurrentValue().GetPath (path, sizeof(path)); 1943 if (path_len > 0) 1944 value.AppendString (path, path_len); 1945 } 1946 else if (var_name == GetSettingNameForPreferDynamicValue()) 1947 { 1948 value.AppendString (g_dynamic_value_types[m_prefer_dynamic_value].string_value); 1949 } 1950 else if (var_name == GetSettingNameForSkipPrologue()) 1951 { 1952 if (m_skip_prologue) 1953 value.AppendString ("true"); 1954 else 1955 value.AppendString ("false"); 1956 } 1957 else if (var_name == GetSettingNameForSourcePathMap ()) 1958 { 1959 } 1960 else if (var_name == GetSettingNameForMaxChildren()) 1961 { 1962 StreamString count_str; 1963 count_str.Printf ("%d", m_max_children_display); 1964 value.AppendString (count_str.GetData()); 1965 } 1966 else if (var_name == GetSettingNameForMaxStringSummaryLength()) 1967 { 1968 StreamString count_str; 1969 count_str.Printf ("%d", m_max_strlen_length); 1970 value.AppendString (count_str.GetData()); 1971 } 1972 else 1973 { 1974 if (err) 1975 err->SetErrorStringWithFormat ("unrecognized variable name '%s'", var_name.AsCString()); 1976 return false; 1977 } 1978 1979 return true; 1980 } 1981 1982 const ConstString 1983 TargetInstanceSettings::CreateInstanceName () 1984 { 1985 StreamString sstr; 1986 static int instance_count = 1; 1987 1988 sstr.Printf ("target_%d", instance_count); 1989 ++instance_count; 1990 1991 const ConstString ret_val (sstr.GetData()); 1992 return ret_val; 1993 } 1994 1995 //-------------------------------------------------- 1996 // Target::SettingsController Variable Tables 1997 //-------------------------------------------------- 1998 OptionEnumValueElement 1999 TargetInstanceSettings::g_dynamic_value_types[] = 2000 { 2001 { eNoDynamicValues, "no-dynamic-values", "Don't calculate the dynamic type of values"}, 2002 { eDynamicCanRunTarget, "run-target", "Calculate the dynamic type of values even if you have to run the target."}, 2003 { eDynamicDontRunTarget, "no-run-target", "Calculate the dynamic type of values, but don't run the target."}, 2004 { 0, NULL, NULL } 2005 }; 2006 2007 SettingEntry 2008 Target::SettingsController::global_settings_table[] = 2009 { 2010 // var-name var-type default enum init'd hidden help-text 2011 // ================= ================== =========== ==== ====== ====== ========================================================================= 2012 { TSC_DEFAULT_ARCH , eSetVarTypeString , NULL , NULL, false, false, "Default architecture to choose, when there's a choice." }, 2013 { NULL , eSetVarTypeNone , NULL , NULL, false, false, NULL } 2014 }; 2015 2016 SettingEntry 2017 Target::SettingsController::instance_settings_table[] = 2018 { 2019 // var-name var-type default enum init'd hidden help-text 2020 // ================= ================== =============== ======================= ====== ====== ========================================================================= 2021 { TSC_EXPR_PREFIX , eSetVarTypeString , NULL , NULL, false, false, "Path to a file containing expressions to be prepended to all expressions." }, 2022 { TSC_PREFER_DYNAMIC , eSetVarTypeEnum , NULL , g_dynamic_value_types, false, false, "Should printed values be shown as their dynamic value." }, 2023 { TSC_SKIP_PROLOGUE , eSetVarTypeBoolean, "true" , NULL, false, false, "Skip function prologues when setting breakpoints by name." }, 2024 { TSC_SOURCE_MAP , eSetVarTypeArray , NULL , NULL, false, false, "Source path remappings to use when locating source files from debug information." }, 2025 { TSC_MAX_CHILDREN , eSetVarTypeInt , "256" , NULL, true, false, "Maximum number of children to expand in any level of depth." }, 2026 { TSC_MAX_STRLENSUMMARY , eSetVarTypeInt , "1024" , NULL, true, false, "Maximum number of characters to show when using %s in summary strings." }, 2027 { NULL , eSetVarTypeNone , NULL , NULL, false, false, NULL } 2028 }; 2029