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