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