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