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