1 //===-- IRExecutionUnit.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 "llvm/ExecutionEngine/ExecutionEngine.h" 11 #include "llvm/IR/Constants.h" 12 #include "llvm/IR/LLVMContext.h" 13 #include "llvm/IR/Module.h" 14 #include "llvm/Support/SourceMgr.h" 15 #include "llvm/Support/raw_ostream.h" 16 17 #include "lldb/Core/DataBufferHeap.h" 18 #include "lldb/Core/DataExtractor.h" 19 #include "lldb/Core/Debugger.h" 20 #include "lldb/Core/Disassembler.h" 21 #include "lldb/Core/Log.h" 22 #include "lldb/Core/Module.h" 23 #include "lldb/Core/Section.h" 24 #include "lldb/Symbol/CompileUnit.h" 25 #include "lldb/Symbol/SymbolContext.h" 26 #include "lldb/Symbol/SymbolVendor.h" 27 #include "lldb/Symbol/SymbolFile.h" 28 #include "lldb/Expression/IRExecutionUnit.h" 29 #include "lldb/Target/ExecutionContext.h" 30 #include "lldb/Target/Target.h" 31 #include "lldb/Target/ObjCLanguageRuntime.h" 32 #include "lldb/Utility/LLDBAssert.h" 33 34 #include "lldb/../../source/Plugins/Language/CPlusPlus/CPlusPlusLanguage.h" 35 36 using namespace lldb_private; 37 38 IRExecutionUnit::IRExecutionUnit (std::unique_ptr<llvm::LLVMContext> &context_ap, 39 std::unique_ptr<llvm::Module> &module_ap, 40 ConstString &name, 41 const lldb::TargetSP &target_sp, 42 const SymbolContext &sym_ctx, 43 std::vector<std::string> &cpu_features) : 44 IRMemoryMap(target_sp), 45 m_context_ap(context_ap.release()), 46 m_module_ap(module_ap.release()), 47 m_module(m_module_ap.get()), 48 m_cpu_features(cpu_features), 49 m_name(name), 50 m_sym_ctx(sym_ctx), 51 m_did_jit(false), 52 m_function_load_addr(LLDB_INVALID_ADDRESS), 53 m_function_end_load_addr(LLDB_INVALID_ADDRESS), 54 m_reported_allocations(false) 55 { 56 } 57 58 lldb::addr_t 59 IRExecutionUnit::WriteNow (const uint8_t *bytes, 60 size_t size, 61 Error &error) 62 { 63 const bool zero_memory = false; 64 lldb::addr_t allocation_process_addr = Malloc (size, 65 8, 66 lldb::ePermissionsWritable | lldb::ePermissionsReadable, 67 eAllocationPolicyMirror, 68 zero_memory, 69 error); 70 71 if (!error.Success()) 72 return LLDB_INVALID_ADDRESS; 73 74 WriteMemory(allocation_process_addr, bytes, size, error); 75 76 if (!error.Success()) 77 { 78 Error err; 79 Free (allocation_process_addr, err); 80 81 return LLDB_INVALID_ADDRESS; 82 } 83 84 if (Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)) 85 { 86 DataBufferHeap my_buffer(size, 0); 87 Error err; 88 ReadMemory(my_buffer.GetBytes(), allocation_process_addr, size, err); 89 90 if (err.Success()) 91 { 92 DataExtractor my_extractor(my_buffer.GetBytes(), my_buffer.GetByteSize(), lldb::eByteOrderBig, 8); 93 my_extractor.PutToLog(log, 0, my_buffer.GetByteSize(), allocation_process_addr, 16, DataExtractor::TypeUInt8); 94 } 95 } 96 97 return allocation_process_addr; 98 } 99 100 void 101 IRExecutionUnit::FreeNow (lldb::addr_t allocation) 102 { 103 if (allocation == LLDB_INVALID_ADDRESS) 104 return; 105 106 Error err; 107 108 Free(allocation, err); 109 } 110 111 Error 112 IRExecutionUnit::DisassembleFunction (Stream &stream, 113 lldb::ProcessSP &process_wp) 114 { 115 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); 116 117 ExecutionContext exe_ctx(process_wp); 118 119 Error ret; 120 121 ret.Clear(); 122 123 lldb::addr_t func_local_addr = LLDB_INVALID_ADDRESS; 124 lldb::addr_t func_remote_addr = LLDB_INVALID_ADDRESS; 125 126 for (JittedFunction &function : m_jitted_functions) 127 { 128 if (function.m_name.AsCString() != m_name.AsCString()) 129 { 130 func_local_addr = function.m_local_addr; 131 func_remote_addr = function.m_remote_addr; 132 } 133 } 134 135 if (func_local_addr == LLDB_INVALID_ADDRESS) 136 { 137 ret.SetErrorToGenericError(); 138 ret.SetErrorStringWithFormat("Couldn't find function %s for disassembly", m_name.AsCString()); 139 return ret; 140 } 141 142 if (log) 143 log->Printf("Found function, has local address 0x%" PRIx64 " and remote address 0x%" PRIx64, (uint64_t)func_local_addr, (uint64_t)func_remote_addr); 144 145 std::pair <lldb::addr_t, lldb::addr_t> func_range; 146 147 func_range = GetRemoteRangeForLocal(func_local_addr); 148 149 if (func_range.first == 0 && func_range.second == 0) 150 { 151 ret.SetErrorToGenericError(); 152 ret.SetErrorStringWithFormat("Couldn't find code range for function %s", m_name.AsCString()); 153 return ret; 154 } 155 156 if (log) 157 log->Printf("Function's code range is [0x%" PRIx64 "+0x%" PRIx64 "]", func_range.first, func_range.second); 158 159 Target *target = exe_ctx.GetTargetPtr(); 160 if (!target) 161 { 162 ret.SetErrorToGenericError(); 163 ret.SetErrorString("Couldn't find the target"); 164 return ret; 165 } 166 167 lldb::DataBufferSP buffer_sp(new DataBufferHeap(func_range.second, 0)); 168 169 Process *process = exe_ctx.GetProcessPtr(); 170 Error err; 171 process->ReadMemory(func_remote_addr, buffer_sp->GetBytes(), buffer_sp->GetByteSize(), err); 172 173 if (!err.Success()) 174 { 175 ret.SetErrorToGenericError(); 176 ret.SetErrorStringWithFormat("Couldn't read from process: %s", err.AsCString("unknown error")); 177 return ret; 178 } 179 180 ArchSpec arch(target->GetArchitecture()); 181 182 const char *plugin_name = NULL; 183 const char *flavor_string = NULL; 184 lldb::DisassemblerSP disassembler_sp = Disassembler::FindPlugin(arch, flavor_string, plugin_name); 185 186 if (!disassembler_sp) 187 { 188 ret.SetErrorToGenericError(); 189 ret.SetErrorStringWithFormat("Unable to find disassembler plug-in for %s architecture.", arch.GetArchitectureName()); 190 return ret; 191 } 192 193 if (!process) 194 { 195 ret.SetErrorToGenericError(); 196 ret.SetErrorString("Couldn't find the process"); 197 return ret; 198 } 199 200 DataExtractor extractor(buffer_sp, 201 process->GetByteOrder(), 202 target->GetArchitecture().GetAddressByteSize()); 203 204 if (log) 205 { 206 log->Printf("Function data has contents:"); 207 extractor.PutToLog (log, 208 0, 209 extractor.GetByteSize(), 210 func_remote_addr, 211 16, 212 DataExtractor::TypeUInt8); 213 } 214 215 disassembler_sp->DecodeInstructions (Address (func_remote_addr), extractor, 0, UINT32_MAX, false, false); 216 217 InstructionList &instruction_list = disassembler_sp->GetInstructionList(); 218 instruction_list.Dump(&stream, true, true, &exe_ctx); 219 220 // FIXME: The DisassemblerLLVMC has a reference cycle and won't go away if it has any active instructions. 221 // I'll fix that but for now, just clear the list and it will go away nicely. 222 disassembler_sp->GetInstructionList().Clear(); 223 return ret; 224 } 225 226 static void ReportInlineAsmError(const llvm::SMDiagnostic &diagnostic, void *Context, unsigned LocCookie) 227 { 228 Error *err = static_cast<Error*>(Context); 229 230 if (err && err->Success()) 231 { 232 err->SetErrorToGenericError(); 233 err->SetErrorStringWithFormat("Inline assembly error: %s", diagnostic.getMessage().str().c_str()); 234 } 235 } 236 237 void 238 IRExecutionUnit::ReportSymbolLookupError(const ConstString &name) 239 { 240 m_failed_lookups.push_back(name); 241 } 242 243 void 244 IRExecutionUnit::GetRunnableInfo(Error &error, 245 lldb::addr_t &func_addr, 246 lldb::addr_t &func_end) 247 { 248 lldb::ProcessSP process_sp(GetProcessWP().lock()); 249 250 static Mutex s_runnable_info_mutex(Mutex::Type::eMutexTypeRecursive); 251 252 func_addr = LLDB_INVALID_ADDRESS; 253 func_end = LLDB_INVALID_ADDRESS; 254 255 if (!process_sp) 256 { 257 error.SetErrorToGenericError(); 258 error.SetErrorString("Couldn't write the JIT compiled code into the process because the process is invalid"); 259 return; 260 } 261 262 if (m_did_jit) 263 { 264 func_addr = m_function_load_addr; 265 func_end = m_function_end_load_addr; 266 267 return; 268 }; 269 270 Mutex::Locker runnable_info_mutex_locker(s_runnable_info_mutex); 271 272 m_did_jit = true; 273 274 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); 275 276 std::string error_string; 277 278 if (log) 279 { 280 std::string s; 281 llvm::raw_string_ostream oss(s); 282 283 m_module->print(oss, NULL); 284 285 oss.flush(); 286 287 log->Printf ("Module being sent to JIT: \n%s", s.c_str()); 288 } 289 290 llvm::Triple triple(m_module->getTargetTriple()); 291 llvm::Reloc::Model relocModel; 292 llvm::CodeModel::Model codeModel; 293 294 if (triple.isOSBinFormatELF()) 295 { 296 relocModel = llvm::Reloc::Static; 297 } 298 else 299 { 300 relocModel = llvm::Reloc::PIC_; 301 } 302 303 // This will be small for 32-bit and large for 64-bit. 304 codeModel = llvm::CodeModel::JITDefault; 305 306 m_module_ap->getContext().setInlineAsmDiagnosticHandler(ReportInlineAsmError, &error); 307 308 llvm::EngineBuilder builder(std::move(m_module_ap)); 309 310 builder.setEngineKind(llvm::EngineKind::JIT) 311 .setErrorStr(&error_string) 312 .setRelocationModel(relocModel) 313 .setMCJITMemoryManager(std::unique_ptr<MemoryManager>(new MemoryManager(*this))) 314 .setCodeModel(codeModel) 315 .setOptLevel(llvm::CodeGenOpt::Less); 316 317 llvm::StringRef mArch; 318 llvm::StringRef mCPU; 319 llvm::SmallVector<std::string, 0> mAttrs; 320 321 for (std::string &feature : m_cpu_features) 322 mAttrs.push_back(feature); 323 324 llvm::TargetMachine *target_machine = builder.selectTarget(triple, 325 mArch, 326 mCPU, 327 mAttrs); 328 329 m_execution_engine_ap.reset(builder.create(target_machine)); 330 331 m_strip_underscore = (m_execution_engine_ap->getDataLayout().getGlobalPrefix() == '_'); 332 333 if (!m_execution_engine_ap.get()) 334 { 335 error.SetErrorToGenericError(); 336 error.SetErrorStringWithFormat("Couldn't JIT the function: %s", error_string.c_str()); 337 return; 338 } 339 340 // Make sure we see all sections, including ones that don't have relocations... 341 m_execution_engine_ap->setProcessAllSections(true); 342 343 m_execution_engine_ap->DisableLazyCompilation(); 344 345 for (llvm::Function &function : *m_module) 346 { 347 if (function.isDeclaration() || function.hasPrivateLinkage()) 348 continue; 349 350 const bool external = function.hasExternalLinkage() || function.hasLinkOnceODRLinkage(); 351 352 void *fun_ptr = m_execution_engine_ap->getPointerToFunction(&function); 353 354 if (!error.Success()) 355 { 356 // We got an error through our callback! 357 return; 358 } 359 360 if (!fun_ptr) 361 { 362 error.SetErrorToGenericError(); 363 error.SetErrorStringWithFormat("'%s' was in the JITted module but wasn't lowered", function.getName().str().c_str()); 364 return; 365 } 366 m_jitted_functions.push_back (JittedFunction(function.getName().str().c_str(), external, (lldb::addr_t)fun_ptr)); 367 } 368 369 CommitAllocations(process_sp); 370 ReportAllocations(*m_execution_engine_ap); 371 372 // We have to do this after calling ReportAllocations because for the MCJIT, getGlobalValueAddress 373 // will cause the JIT to perform all relocations. That can only be done once, and has to happen 374 // after we do the remapping from local -> remote. 375 // That means we don't know the local address of the Variables, but we don't need that for anything, 376 // so that's okay. 377 378 std::function<void (llvm::GlobalValue &)> RegisterOneValue = [this] (llvm::GlobalValue &val) { 379 if (val.hasExternalLinkage() && !val.isDeclaration()) 380 { 381 uint64_t var_ptr_addr = m_execution_engine_ap->getGlobalValueAddress(val.getName().str()); 382 383 lldb::addr_t remote_addr = GetRemoteAddressForLocal(var_ptr_addr); 384 385 // This is a really unfortunae API that sometimes returns local addresses and sometimes returns remote addresses, based on whether 386 // the variable was relocated during ReportAllocations or not. 387 388 if (remote_addr == LLDB_INVALID_ADDRESS) 389 { 390 remote_addr = var_ptr_addr; 391 } 392 393 if (var_ptr_addr != 0) 394 m_jitted_global_variables.push_back (JittedGlobalVariable (val.getName().str().c_str(), LLDB_INVALID_ADDRESS, remote_addr)); 395 } 396 }; 397 398 for (llvm::GlobalVariable &global_var : m_module->getGlobalList()) 399 { 400 RegisterOneValue(global_var); 401 } 402 403 for (llvm::GlobalAlias &global_alias : m_module->getAliasList()) 404 { 405 RegisterOneValue(global_alias); 406 } 407 408 WriteData(process_sp); 409 410 if (m_failed_lookups.size()) 411 { 412 StreamString ss; 413 414 ss.PutCString("Couldn't lookup symbols:\n"); 415 416 bool emitNewLine = false; 417 418 for (const ConstString &failed_lookup : m_failed_lookups) 419 { 420 if (emitNewLine) 421 ss.PutCString("\n"); 422 emitNewLine = true; 423 ss.PutCString(" "); 424 ss.PutCString(Mangled(failed_lookup).GetDemangledName(lldb::eLanguageTypeObjC_plus_plus).AsCString()); 425 } 426 427 m_failed_lookups.clear(); 428 429 error.SetErrorString(ss.GetData()); 430 431 return; 432 } 433 434 m_function_load_addr = LLDB_INVALID_ADDRESS; 435 m_function_end_load_addr = LLDB_INVALID_ADDRESS; 436 437 for (JittedFunction &jitted_function : m_jitted_functions) 438 { 439 jitted_function.m_remote_addr = GetRemoteAddressForLocal (jitted_function.m_local_addr); 440 441 if (!m_name.IsEmpty() && jitted_function.m_name == m_name) 442 { 443 AddrRange func_range = GetRemoteRangeForLocal(jitted_function.m_local_addr); 444 m_function_end_load_addr = func_range.first + func_range.second; 445 m_function_load_addr = jitted_function.m_remote_addr; 446 } 447 } 448 449 if (log) 450 { 451 log->Printf("Code can be run in the target."); 452 453 StreamString disassembly_stream; 454 455 Error err = DisassembleFunction(disassembly_stream, process_sp); 456 457 if (!err.Success()) 458 { 459 log->Printf("Couldn't disassemble function : %s", err.AsCString("unknown error")); 460 } 461 else 462 { 463 log->Printf("Function disassembly:\n%s", disassembly_stream.GetData()); 464 } 465 466 log->Printf("Sections: "); 467 for (AllocationRecord &record : m_records) 468 { 469 if (record.m_process_address != LLDB_INVALID_ADDRESS) 470 { 471 record.dump(log); 472 473 DataBufferHeap my_buffer(record.m_size, 0); 474 Error err; 475 ReadMemory(my_buffer.GetBytes(), record.m_process_address, record.m_size, err); 476 477 if (err.Success()) 478 { 479 DataExtractor my_extractor(my_buffer.GetBytes(), my_buffer.GetByteSize(), lldb::eByteOrderBig, 8); 480 my_extractor.PutToLog(log, 0, my_buffer.GetByteSize(), record.m_process_address, 16, DataExtractor::TypeUInt8); 481 } 482 } 483 else 484 { 485 record.dump(log); 486 487 DataExtractor my_extractor ((const void*)record.m_host_address, record.m_size, lldb::eByteOrderBig, 8); 488 my_extractor.PutToLog(log, 0, record.m_size, record.m_host_address, 16, DataExtractor::TypeUInt8); 489 } 490 } 491 } 492 493 func_addr = m_function_load_addr; 494 func_end = m_function_end_load_addr; 495 496 return; 497 } 498 499 IRExecutionUnit::~IRExecutionUnit () 500 { 501 m_module_ap.reset(); 502 m_execution_engine_ap.reset(); 503 m_context_ap.reset(); 504 } 505 506 IRExecutionUnit::MemoryManager::MemoryManager (IRExecutionUnit &parent) : 507 m_default_mm_ap (new llvm::SectionMemoryManager()), 508 m_parent (parent) 509 { 510 } 511 512 IRExecutionUnit::MemoryManager::~MemoryManager () 513 { 514 } 515 516 lldb::SectionType 517 IRExecutionUnit::GetSectionTypeFromSectionName (const llvm::StringRef &name, IRExecutionUnit::AllocationKind alloc_kind) 518 { 519 lldb::SectionType sect_type = lldb::eSectionTypeCode; 520 switch (alloc_kind) 521 { 522 case AllocationKind::Stub: sect_type = lldb::eSectionTypeCode; break; 523 case AllocationKind::Code: sect_type = lldb::eSectionTypeCode; break; 524 case AllocationKind::Data: sect_type = lldb::eSectionTypeData; break; 525 case AllocationKind::Global:sect_type = lldb::eSectionTypeData; break; 526 case AllocationKind::Bytes: sect_type = lldb::eSectionTypeOther; break; 527 } 528 529 if (!name.empty()) 530 { 531 if (name.equals("__text") || name.equals(".text")) 532 sect_type = lldb::eSectionTypeCode; 533 else if (name.equals("__data") || name.equals(".data")) 534 sect_type = lldb::eSectionTypeCode; 535 else if (name.startswith("__debug_") || name.startswith(".debug_")) 536 { 537 const uint32_t name_idx = name[0] == '_' ? 8 : 7; 538 llvm::StringRef dwarf_name(name.substr(name_idx)); 539 switch (dwarf_name[0]) 540 { 541 case 'a': 542 if (dwarf_name.equals("abbrev")) 543 sect_type = lldb::eSectionTypeDWARFDebugAbbrev; 544 else if (dwarf_name.equals("aranges")) 545 sect_type = lldb::eSectionTypeDWARFDebugAranges; 546 else if (dwarf_name.equals("addr")) 547 sect_type = lldb::eSectionTypeDWARFDebugAddr; 548 break; 549 550 case 'f': 551 if (dwarf_name.equals("frame")) 552 sect_type = lldb::eSectionTypeDWARFDebugFrame; 553 break; 554 555 case 'i': 556 if (dwarf_name.equals("info")) 557 sect_type = lldb::eSectionTypeDWARFDebugInfo; 558 break; 559 560 case 'l': 561 if (dwarf_name.equals("line")) 562 sect_type = lldb::eSectionTypeDWARFDebugLine; 563 else if (dwarf_name.equals("loc")) 564 sect_type = lldb::eSectionTypeDWARFDebugLoc; 565 break; 566 567 case 'm': 568 if (dwarf_name.equals("macinfo")) 569 sect_type = lldb::eSectionTypeDWARFDebugMacInfo; 570 break; 571 572 case 'p': 573 if (dwarf_name.equals("pubnames")) 574 sect_type = lldb::eSectionTypeDWARFDebugPubNames; 575 else if (dwarf_name.equals("pubtypes")) 576 sect_type = lldb::eSectionTypeDWARFDebugPubTypes; 577 break; 578 579 case 's': 580 if (dwarf_name.equals("str")) 581 sect_type = lldb::eSectionTypeDWARFDebugStr; 582 else if (dwarf_name.equals("str_offsets")) 583 sect_type = lldb::eSectionTypeDWARFDebugStrOffsets; 584 break; 585 586 case 'r': 587 if (dwarf_name.equals("ranges")) 588 sect_type = lldb::eSectionTypeDWARFDebugRanges; 589 break; 590 591 default: 592 break; 593 } 594 } 595 else if (name.startswith("__apple_") || name.startswith(".apple_")) 596 { 597 #if 0 598 const uint32_t name_idx = name[0] == '_' ? 8 : 7; 599 llvm::StringRef apple_name(name.substr(name_idx)); 600 switch (apple_name[0]) 601 { 602 case 'n': 603 if (apple_name.equals("names")) 604 sect_type = lldb::eSectionTypeDWARFAppleNames; 605 else if (apple_name.equals("namespac") || apple_name.equals("namespaces")) 606 sect_type = lldb::eSectionTypeDWARFAppleNamespaces; 607 break; 608 case 't': 609 if (apple_name.equals("types")) 610 sect_type = lldb::eSectionTypeDWARFAppleTypes; 611 break; 612 case 'o': 613 if (apple_name.equals("objc")) 614 sect_type = lldb::eSectionTypeDWARFAppleObjC; 615 break; 616 default: 617 break; 618 } 619 #else 620 sect_type = lldb::eSectionTypeInvalid; 621 #endif 622 } 623 else if (name.equals("__objc_imageinfo")) 624 sect_type = lldb::eSectionTypeOther; 625 } 626 return sect_type; 627 } 628 629 uint8_t * 630 IRExecutionUnit::MemoryManager::allocateCodeSection(uintptr_t Size, 631 unsigned Alignment, 632 unsigned SectionID, 633 llvm::StringRef SectionName) 634 { 635 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); 636 637 uint8_t *return_value = m_default_mm_ap->allocateCodeSection(Size, Alignment, SectionID, SectionName); 638 639 m_parent.m_records.push_back(AllocationRecord((uintptr_t)return_value, 640 lldb::ePermissionsReadable | lldb::ePermissionsExecutable, 641 GetSectionTypeFromSectionName (SectionName, AllocationKind::Code), 642 Size, 643 Alignment, 644 SectionID, 645 SectionName.str().c_str())); 646 647 if (log) 648 { 649 log->Printf("IRExecutionUnit::allocateCodeSection(Size=0x%" PRIx64 ", Alignment=%u, SectionID=%u) = %p", 650 (uint64_t)Size, Alignment, SectionID, (void *)return_value); 651 } 652 653 if (m_parent.m_reported_allocations) 654 { 655 Error err; 656 lldb::ProcessSP process_sp = m_parent.GetBestExecutionContextScope()->CalculateProcess(); 657 658 m_parent.CommitOneAllocation(process_sp, err, m_parent.m_records.back()); 659 } 660 661 return return_value; 662 } 663 664 uint8_t * 665 IRExecutionUnit::MemoryManager::allocateDataSection(uintptr_t Size, 666 unsigned Alignment, 667 unsigned SectionID, 668 llvm::StringRef SectionName, 669 bool IsReadOnly) 670 { 671 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); 672 673 uint8_t *return_value = m_default_mm_ap->allocateDataSection(Size, Alignment, SectionID, SectionName, IsReadOnly); 674 675 uint32_t permissions = lldb::ePermissionsReadable; 676 if (!IsReadOnly) 677 permissions |= lldb::ePermissionsWritable; 678 m_parent.m_records.push_back(AllocationRecord((uintptr_t)return_value, 679 permissions, 680 GetSectionTypeFromSectionName (SectionName, AllocationKind::Data), 681 Size, 682 Alignment, 683 SectionID, 684 SectionName.str().c_str())); 685 if (log) 686 { 687 log->Printf("IRExecutionUnit::allocateDataSection(Size=0x%" PRIx64 ", Alignment=%u, SectionID=%u) = %p", 688 (uint64_t)Size, Alignment, SectionID, (void *)return_value); 689 } 690 691 if (m_parent.m_reported_allocations) 692 { 693 Error err; 694 lldb::ProcessSP process_sp = m_parent.GetBestExecutionContextScope()->CalculateProcess(); 695 696 m_parent.CommitOneAllocation(process_sp, err, m_parent.m_records.back()); 697 } 698 699 return return_value; 700 } 701 702 static ConstString 703 FindBestAlternateMangledName(const ConstString &demangled, 704 const lldb::LanguageType &lang_type, 705 const SymbolContext &sym_ctx) 706 { 707 CPlusPlusLanguage::MethodName cpp_name(demangled); 708 std::string scope_qualified_name = cpp_name.GetScopeQualifiedName(); 709 710 if (!scope_qualified_name.size()) 711 return ConstString(); 712 713 if (!sym_ctx.module_sp) 714 return ConstString(); 715 716 SymbolVendor *sym_vendor = sym_ctx.module_sp->GetSymbolVendor(); 717 if (!sym_vendor) 718 return ConstString(); 719 720 lldb_private::SymbolFile *sym_file = sym_vendor->GetSymbolFile(); 721 if (!sym_file) 722 return ConstString(); 723 724 std::vector<ConstString> alternates; 725 sym_file->GetMangledNamesForFunction(scope_qualified_name, alternates); 726 727 std::vector<ConstString> param_and_qual_matches; 728 std::vector<ConstString> param_matches; 729 for (size_t i = 0; i < alternates.size(); i++) 730 { 731 ConstString alternate_mangled_name = alternates[i]; 732 Mangled mangled(alternate_mangled_name, true); 733 ConstString demangled = mangled.GetDemangledName(lang_type); 734 735 CPlusPlusLanguage::MethodName alternate_cpp_name(demangled); 736 if (!cpp_name.IsValid()) 737 continue; 738 739 if (alternate_cpp_name.GetArguments() == cpp_name.GetArguments()) 740 { 741 if (alternate_cpp_name.GetQualifiers() == cpp_name.GetQualifiers()) 742 param_and_qual_matches.push_back(alternate_mangled_name); 743 else 744 param_matches.push_back(alternate_mangled_name); 745 } 746 } 747 748 if (param_and_qual_matches.size()) 749 return param_and_qual_matches[0]; // It is assumed that there will be only one! 750 else if (param_matches.size()) 751 return param_matches[0]; // Return one of them as a best match 752 else 753 return ConstString(); 754 } 755 756 struct IRExecutionUnit::SearchSpec 757 { 758 ConstString name; 759 uint32_t mask; 760 761 SearchSpec(ConstString n, uint32_t m = lldb::eFunctionNameTypeAuto) : 762 name(n), 763 mask(m) 764 { 765 } 766 }; 767 768 void 769 IRExecutionUnit::CollectCandidateCNames(std::vector<IRExecutionUnit::SearchSpec> &C_specs, const ConstString &name) 770 { 771 if (m_strip_underscore && name.AsCString()[0] == '_') 772 C_specs.insert(C_specs.begin(), ConstString(&name.AsCString()[1])); 773 C_specs.push_back(SearchSpec(name)); 774 } 775 776 void 777 IRExecutionUnit::CollectCandidateCPlusPlusNames(std::vector<IRExecutionUnit::SearchSpec> &CPP_specs, const std::vector<SearchSpec> &C_specs, const SymbolContext &sc) 778 { 779 for (const SearchSpec &C_spec : C_specs) 780 { 781 const ConstString &name = C_spec.name; 782 783 if (CPlusPlusLanguage::IsCPPMangledName(name.GetCString())) 784 { 785 Mangled mangled(name, true); 786 ConstString demangled = mangled.GetDemangledName(lldb::eLanguageTypeC_plus_plus); 787 788 if (demangled) 789 { 790 ConstString best_alternate_mangled_name = FindBestAlternateMangledName(demangled, lldb::eLanguageTypeC_plus_plus, sc); 791 792 if (best_alternate_mangled_name) 793 { 794 CPP_specs.push_back(best_alternate_mangled_name); 795 } 796 797 CPP_specs.push_back(SearchSpec(demangled, lldb::eFunctionNameTypeFull)); 798 } 799 } 800 801 // Maybe we're looking for a const symbol but the debug info told us it was const... 802 if (!strncmp(name.GetCString(), "_ZN", 3) && 803 strncmp(name.GetCString(), "_ZNK", 4)) 804 { 805 std::string fixed_scratch("_ZNK"); 806 fixed_scratch.append(name.GetCString() + 3); 807 CPP_specs.push_back(ConstString(fixed_scratch.c_str())); 808 } 809 810 // Maybe we're looking for a static symbol but we thought it was global... 811 if (!strncmp(name.GetCString(), "_Z", 2) && 812 strncmp(name.GetCString(), "_ZL", 3)) 813 { 814 std::string fixed_scratch("_ZL"); 815 fixed_scratch.append(name.GetCString() + 2); 816 CPP_specs.push_back(ConstString(fixed_scratch.c_str())); 817 } 818 819 } 820 } 821 822 lldb::addr_t 823 IRExecutionUnit::FindInSymbols(const std::vector<IRExecutionUnit::SearchSpec> &specs, const lldb_private::SymbolContext &sc) 824 { 825 Target *target = sc.target_sp.get(); 826 827 if (!target) 828 { 829 // we shouldn't be doing any symbol lookup at all without a target 830 return LLDB_INVALID_ADDRESS; 831 } 832 833 for (const SearchSpec &spec : specs) 834 { 835 SymbolContextList sc_list; 836 837 lldb::addr_t best_internal_load_address = LLDB_INVALID_ADDRESS; 838 839 std::function<bool (lldb::addr_t &, SymbolContextList &, const lldb_private::SymbolContext &)> get_external_load_address = 840 [&best_internal_load_address, target](lldb::addr_t &load_address, 841 SymbolContextList &sc_list, 842 const lldb_private::SymbolContext &sc) -> lldb::addr_t 843 { 844 load_address = LLDB_INVALID_ADDRESS; 845 846 for (size_t si = 0, se = sc_list.GetSize(); si < se; ++si) 847 { 848 SymbolContext candidate_sc; 849 850 sc_list.GetContextAtIndex(si, candidate_sc); 851 852 const bool is_external = (candidate_sc.function) || 853 (candidate_sc.symbol && candidate_sc.symbol->IsExternal()); 854 if (candidate_sc.symbol) 855 { 856 load_address = candidate_sc.symbol->ResolveCallableAddress(*target); 857 858 if (load_address == LLDB_INVALID_ADDRESS) 859 { 860 if (target->GetProcessSP()) 861 load_address = candidate_sc.symbol->GetAddress().GetLoadAddress(target); 862 else 863 load_address = candidate_sc.symbol->GetAddress().GetFileAddress(); 864 } 865 } 866 867 if (load_address == LLDB_INVALID_ADDRESS && candidate_sc.function) 868 { 869 if (target->GetProcessSP()) 870 load_address = candidate_sc.function->GetAddressRange().GetBaseAddress().GetLoadAddress(target); 871 else 872 load_address = candidate_sc.function->GetAddressRange().GetBaseAddress().GetFileAddress(); 873 } 874 875 if (load_address != LLDB_INVALID_ADDRESS) 876 { 877 if (is_external) 878 { 879 return true; 880 } 881 else if (best_internal_load_address == LLDB_INVALID_ADDRESS) 882 { 883 best_internal_load_address = load_address; 884 load_address = LLDB_INVALID_ADDRESS; 885 } 886 } 887 } 888 889 return false; 890 }; 891 892 if (sc.module_sp) 893 { 894 sc.module_sp->FindFunctions(spec.name, 895 NULL, 896 spec.mask, 897 true, // include_symbols 898 false, // include_inlines 899 true, // append 900 sc_list); 901 } 902 903 lldb::addr_t load_address = LLDB_INVALID_ADDRESS; 904 905 if (get_external_load_address(load_address, sc_list, sc)) 906 { 907 return load_address; 908 } 909 else 910 { 911 sc_list.Clear(); 912 } 913 914 if (sc_list.GetSize() == 0 && sc.target_sp) 915 { 916 sc.target_sp->GetImages().FindFunctions(spec.name, 917 spec.mask, 918 true, // include_symbols 919 false, // include_inlines 920 true, // append 921 sc_list); 922 } 923 924 if (get_external_load_address(load_address, sc_list, sc)) 925 { 926 return load_address; 927 } 928 else 929 { 930 sc_list.Clear(); 931 } 932 933 if (sc_list.GetSize() == 0 && sc.target_sp) 934 { 935 sc.target_sp->GetImages().FindSymbolsWithNameAndType(spec.name, lldb::eSymbolTypeAny, sc_list); 936 } 937 938 if (get_external_load_address(load_address, sc_list, sc)) 939 { 940 return load_address; 941 } 942 // if there are any searches we try after this, add an sc_list.Clear() in an "else" clause here 943 944 if (best_internal_load_address != LLDB_INVALID_ADDRESS) 945 { 946 return best_internal_load_address; 947 } 948 } 949 950 return LLDB_INVALID_ADDRESS; 951 } 952 953 lldb::addr_t 954 IRExecutionUnit::FindInRuntimes(const std::vector<SearchSpec> &specs, const lldb_private::SymbolContext &sc) 955 { 956 lldb::TargetSP target_sp = sc.target_sp; 957 958 if (!target_sp) 959 { 960 return LLDB_INVALID_ADDRESS; 961 } 962 963 lldb::ProcessSP process_sp = sc.target_sp->GetProcessSP(); 964 965 if (!process_sp) 966 { 967 return LLDB_INVALID_ADDRESS; 968 } 969 970 ObjCLanguageRuntime *runtime = process_sp->GetObjCLanguageRuntime(); 971 972 if (runtime) 973 { 974 for (const SearchSpec &spec : specs) 975 { 976 lldb::addr_t symbol_load_addr = runtime->LookupRuntimeSymbol(spec.name); 977 978 if (symbol_load_addr != LLDB_INVALID_ADDRESS) 979 return symbol_load_addr; 980 } 981 } 982 983 return LLDB_INVALID_ADDRESS; 984 } 985 986 lldb::addr_t 987 IRExecutionUnit::FindInUserDefinedSymbols(const std::vector<SearchSpec> &specs, const lldb_private::SymbolContext &sc) 988 { 989 lldb::TargetSP target_sp = sc.target_sp; 990 991 for (const SearchSpec &spec : specs) 992 { 993 lldb::addr_t symbol_load_addr = target_sp->GetPersistentSymbol(spec.name); 994 995 if (symbol_load_addr != LLDB_INVALID_ADDRESS) 996 return symbol_load_addr; 997 } 998 999 return LLDB_INVALID_ADDRESS; 1000 } 1001 1002 lldb::addr_t 1003 IRExecutionUnit::FindSymbol(const lldb_private::ConstString &name) 1004 { 1005 std::vector<SearchSpec> candidate_C_names; 1006 std::vector<SearchSpec> candidate_CPlusPlus_names; 1007 1008 CollectCandidateCNames(candidate_C_names, name); 1009 1010 lldb::addr_t ret = FindInSymbols(candidate_C_names, m_sym_ctx); 1011 if (ret == LLDB_INVALID_ADDRESS) 1012 ret = FindInRuntimes(candidate_C_names, m_sym_ctx); 1013 1014 if (ret == LLDB_INVALID_ADDRESS) 1015 ret = FindInUserDefinedSymbols(candidate_C_names, m_sym_ctx); 1016 1017 if (ret == LLDB_INVALID_ADDRESS) 1018 { 1019 CollectCandidateCPlusPlusNames(candidate_CPlusPlus_names, candidate_C_names, m_sym_ctx); 1020 ret = FindInSymbols(candidate_CPlusPlus_names, m_sym_ctx); 1021 } 1022 1023 return ret; 1024 } 1025 1026 void 1027 IRExecutionUnit::GetStaticInitializers(std::vector <lldb::addr_t> &static_initializers) 1028 { 1029 if (llvm::GlobalVariable *global_ctors = m_module->getNamedGlobal("llvm.global_ctors")) 1030 { 1031 if (llvm::ConstantArray *ctor_array = llvm::dyn_cast<llvm::ConstantArray>(global_ctors->getInitializer())) 1032 { 1033 for (llvm::Use &ctor_use : ctor_array->operands()) 1034 { 1035 if (llvm::ConstantStruct *ctor_struct = llvm::dyn_cast<llvm::ConstantStruct>(ctor_use)) 1036 { 1037 lldbassert(ctor_struct->getNumOperands() == 3); // this is standardized 1038 if (llvm::Function *ctor_function = llvm::dyn_cast<llvm::Function>(ctor_struct->getOperand(1))) 1039 { 1040 ctor_function->dump(); 1041 1042 ConstString ctor_function_name_cs(ctor_function->getName().str()); 1043 1044 for (JittedFunction &jitted_function : m_jitted_functions) 1045 { 1046 if (ctor_function_name_cs == jitted_function.m_name) 1047 { 1048 if (jitted_function.m_remote_addr != LLDB_INVALID_ADDRESS) 1049 { 1050 static_initializers.push_back(jitted_function.m_remote_addr); 1051 } 1052 break; 1053 } 1054 } 1055 } 1056 } 1057 } 1058 } 1059 } 1060 } 1061 1062 uint64_t 1063 IRExecutionUnit::MemoryManager::getSymbolAddress(const std::string &Name) 1064 { 1065 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); 1066 1067 ConstString name_cs(Name.c_str()); 1068 1069 lldb::addr_t ret = m_parent.FindSymbol(name_cs); 1070 1071 if (ret == LLDB_INVALID_ADDRESS) 1072 { 1073 if (log) 1074 log->Printf("IRExecutionUnit::getSymbolAddress(Name=\"%s\") = <not found>", 1075 Name.c_str()); 1076 1077 m_parent.ReportSymbolLookupError(name_cs); 1078 return 0xbad0bad0; 1079 } 1080 else 1081 { 1082 if (log) 1083 log->Printf("IRExecutionUnit::getSymbolAddress(Name=\"%s\") = %" PRIx64, 1084 Name.c_str(), 1085 ret); 1086 return ret; 1087 } 1088 } 1089 1090 void * 1091 IRExecutionUnit::MemoryManager::getPointerToNamedFunction(const std::string &Name, 1092 bool AbortOnFailure) { 1093 assert (sizeof(void *) == 8); 1094 1095 return (void*)getSymbolAddress(Name); 1096 } 1097 1098 lldb::addr_t 1099 IRExecutionUnit::GetRemoteAddressForLocal (lldb::addr_t local_address) 1100 { 1101 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); 1102 1103 for (AllocationRecord &record : m_records) 1104 { 1105 if (local_address >= record.m_host_address && 1106 local_address < record.m_host_address + record.m_size) 1107 { 1108 if (record.m_process_address == LLDB_INVALID_ADDRESS) 1109 return LLDB_INVALID_ADDRESS; 1110 1111 lldb::addr_t ret = record.m_process_address + (local_address - record.m_host_address); 1112 1113 if (log) 1114 { 1115 log->Printf("IRExecutionUnit::GetRemoteAddressForLocal() found 0x%" PRIx64 " in [0x%" PRIx64 "..0x%" PRIx64 "], and returned 0x%" PRIx64 " from [0x%" PRIx64 "..0x%" PRIx64 "].", 1116 local_address, 1117 (uint64_t)record.m_host_address, 1118 (uint64_t)record.m_host_address + (uint64_t)record.m_size, 1119 ret, 1120 record.m_process_address, 1121 record.m_process_address + record.m_size); 1122 } 1123 1124 return ret; 1125 } 1126 } 1127 1128 return LLDB_INVALID_ADDRESS; 1129 } 1130 1131 IRExecutionUnit::AddrRange 1132 IRExecutionUnit::GetRemoteRangeForLocal (lldb::addr_t local_address) 1133 { 1134 for (AllocationRecord &record : m_records) 1135 { 1136 if (local_address >= record.m_host_address && 1137 local_address < record.m_host_address + record.m_size) 1138 { 1139 if (record.m_process_address == LLDB_INVALID_ADDRESS) 1140 return AddrRange(0, 0); 1141 1142 return AddrRange(record.m_process_address, record.m_size); 1143 } 1144 } 1145 1146 return AddrRange (0, 0); 1147 } 1148 1149 bool 1150 IRExecutionUnit::CommitOneAllocation (lldb::ProcessSP &process_sp, 1151 Error &error, 1152 AllocationRecord &record) 1153 { 1154 if (record.m_process_address != LLDB_INVALID_ADDRESS) 1155 { 1156 return true; 1157 } 1158 1159 switch (record.m_sect_type) 1160 { 1161 case lldb::eSectionTypeInvalid: 1162 case lldb::eSectionTypeDWARFDebugAbbrev: 1163 case lldb::eSectionTypeDWARFDebugAddr: 1164 case lldb::eSectionTypeDWARFDebugAranges: 1165 case lldb::eSectionTypeDWARFDebugFrame: 1166 case lldb::eSectionTypeDWARFDebugInfo: 1167 case lldb::eSectionTypeDWARFDebugLine: 1168 case lldb::eSectionTypeDWARFDebugLoc: 1169 case lldb::eSectionTypeDWARFDebugMacInfo: 1170 case lldb::eSectionTypeDWARFDebugPubNames: 1171 case lldb::eSectionTypeDWARFDebugPubTypes: 1172 case lldb::eSectionTypeDWARFDebugRanges: 1173 case lldb::eSectionTypeDWARFDebugStr: 1174 case lldb::eSectionTypeDWARFDebugStrOffsets: 1175 case lldb::eSectionTypeDWARFAppleNames: 1176 case lldb::eSectionTypeDWARFAppleTypes: 1177 case lldb::eSectionTypeDWARFAppleNamespaces: 1178 case lldb::eSectionTypeDWARFAppleObjC: 1179 error.Clear(); 1180 break; 1181 default: 1182 const bool zero_memory = false; 1183 record.m_process_address = Malloc (record.m_size, 1184 record.m_alignment, 1185 record.m_permissions, 1186 eAllocationPolicyProcessOnly, 1187 zero_memory, 1188 error); 1189 break; 1190 } 1191 1192 return error.Success(); 1193 } 1194 1195 bool 1196 IRExecutionUnit::CommitAllocations (lldb::ProcessSP &process_sp) 1197 { 1198 bool ret = true; 1199 1200 lldb_private::Error err; 1201 1202 for (AllocationRecord &record : m_records) 1203 { 1204 ret = CommitOneAllocation(process_sp, err, record); 1205 1206 if (!ret) 1207 { 1208 break; 1209 } 1210 } 1211 1212 if (!ret) 1213 { 1214 for (AllocationRecord &record : m_records) 1215 { 1216 if (record.m_process_address != LLDB_INVALID_ADDRESS) 1217 { 1218 Free(record.m_process_address, err); 1219 record.m_process_address = LLDB_INVALID_ADDRESS; 1220 } 1221 } 1222 } 1223 1224 return ret; 1225 } 1226 1227 void 1228 IRExecutionUnit::ReportAllocations (llvm::ExecutionEngine &engine) 1229 { 1230 m_reported_allocations = true; 1231 1232 for (AllocationRecord &record : m_records) 1233 { 1234 if (record.m_process_address == LLDB_INVALID_ADDRESS) 1235 continue; 1236 1237 if (record.m_section_id == eSectionIDInvalid) 1238 continue; 1239 1240 engine.mapSectionAddress((void*)record.m_host_address, record.m_process_address); 1241 } 1242 1243 // Trigger re-application of relocations. 1244 engine.finalizeObject(); 1245 } 1246 1247 bool 1248 IRExecutionUnit::WriteData (lldb::ProcessSP &process_sp) 1249 { 1250 bool wrote_something = false; 1251 for (AllocationRecord &record : m_records) 1252 { 1253 if (record.m_process_address != LLDB_INVALID_ADDRESS) 1254 { 1255 lldb_private::Error err; 1256 WriteMemory (record.m_process_address, (uint8_t*)record.m_host_address, record.m_size, err); 1257 if (err.Success()) 1258 wrote_something = true; 1259 } 1260 } 1261 return wrote_something; 1262 } 1263 1264 void 1265 IRExecutionUnit::AllocationRecord::dump (Log *log) 1266 { 1267 if (!log) 1268 return; 1269 1270 log->Printf("[0x%llx+0x%llx]->0x%llx (alignment %d, section ID %d, name %s)", 1271 (unsigned long long)m_host_address, 1272 (unsigned long long)m_size, 1273 (unsigned long long)m_process_address, 1274 (unsigned)m_alignment, 1275 (unsigned)m_section_id, 1276 m_name.c_str()); 1277 } 1278 1279 1280 lldb::ByteOrder 1281 IRExecutionUnit::GetByteOrder () const 1282 { 1283 ExecutionContext exe_ctx (GetBestExecutionContextScope()); 1284 return exe_ctx.GetByteOrder(); 1285 } 1286 1287 uint32_t 1288 IRExecutionUnit::GetAddressByteSize () const 1289 { 1290 ExecutionContext exe_ctx (GetBestExecutionContextScope()); 1291 return exe_ctx.GetAddressByteSize(); 1292 } 1293 1294 void 1295 IRExecutionUnit::PopulateSymtab (lldb_private::ObjectFile *obj_file, 1296 lldb_private::Symtab &symtab) 1297 { 1298 // No symbols yet... 1299 } 1300 1301 1302 void 1303 IRExecutionUnit::PopulateSectionList (lldb_private::ObjectFile *obj_file, 1304 lldb_private::SectionList §ion_list) 1305 { 1306 for (AllocationRecord &record : m_records) 1307 { 1308 if (record.m_size > 0) 1309 { 1310 lldb::SectionSP section_sp (new lldb_private::Section (obj_file->GetModule(), 1311 obj_file, 1312 record.m_section_id, 1313 ConstString(record.m_name), 1314 record.m_sect_type, 1315 record.m_process_address, 1316 record.m_size, 1317 record.m_host_address, // file_offset (which is the host address for the data) 1318 record.m_size, // file_size 1319 0, 1320 record.m_permissions)); // flags 1321 section_list.AddSection (section_sp); 1322 } 1323 } 1324 } 1325 1326 bool 1327 IRExecutionUnit::GetArchitecture (lldb_private::ArchSpec &arch) 1328 { 1329 ExecutionContext exe_ctx (GetBestExecutionContextScope()); 1330 Target *target = exe_ctx.GetTargetPtr(); 1331 if (target) 1332 arch = target->GetArchitecture(); 1333 else 1334 arch.Clear(); 1335 return arch.IsValid(); 1336 } 1337 1338 lldb::ModuleSP 1339 IRExecutionUnit::GetJITModule () 1340 { 1341 ExecutionContext exe_ctx (GetBestExecutionContextScope()); 1342 Target *target = exe_ctx.GetTargetPtr(); 1343 if (target) 1344 { 1345 lldb::ModuleSP jit_module_sp = lldb_private::Module::CreateJITModule (std::static_pointer_cast<lldb_private::ObjectFileJITDelegate>(shared_from_this())); 1346 if (jit_module_sp) 1347 { 1348 bool changed = false; 1349 jit_module_sp->SetLoadAddress(*target, 0, true, changed); 1350 } 1351 return jit_module_sp; 1352 } 1353 return lldb::ModuleSP(); 1354 } 1355