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