1 //===-- IRExecutionUnit.cpp -------------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
12 // Other libraries and framework includes
13 #include "llvm/ExecutionEngine/ExecutionEngine.h"
14 #include "llvm/IR/LLVMContext.h"
15 #include "llvm/IR/Module.h"
16 #include "llvm/Support/SourceMgr.h"
18 #include "lldb/Core/DataBufferHeap.h"
19 #include "lldb/Core/DataExtractor.h"
20 #include "lldb/Core/Disassembler.h"
21 #include "lldb/Core/Log.h"
22 #include "lldb/Expression/IRExecutionUnit.h"
23 #include "lldb/Target/ExecutionContext.h"
24 #include "lldb/Target/Target.h"
26 using namespace lldb_private;
28 IRExecutionUnit::IRExecutionUnit (std::unique_ptr<llvm::LLVMContext> &context_ap,
29 std::unique_ptr<llvm::Module> &module_ap,
31 const lldb::TargetSP &target_sp,
32 std::vector<std::string> &cpu_features) :
33 IRMemoryMap(target_sp),
34 m_context_ap(context_ap.release()),
35 m_module_ap(module_ap.release()),
36 m_module(m_module_ap.get()),
37 m_cpu_features(cpu_features),
40 m_function_load_addr(LLDB_INVALID_ADDRESS),
41 m_function_end_load_addr(LLDB_INVALID_ADDRESS)
46 IRExecutionUnit::WriteNow (const uint8_t *bytes,
50 lldb::addr_t allocation_process_addr = Malloc (size,
52 lldb::ePermissionsWritable | lldb::ePermissionsReadable,
53 eAllocationPolicyMirror,
57 return LLDB_INVALID_ADDRESS;
59 WriteMemory(allocation_process_addr, bytes, size, error);
64 Free (allocation_process_addr, err);
66 return LLDB_INVALID_ADDRESS;
69 if (Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS))
71 DataBufferHeap my_buffer(size, 0);
73 ReadMemory(my_buffer.GetBytes(), allocation_process_addr, size, err);
77 DataExtractor my_extractor(my_buffer.GetBytes(), my_buffer.GetByteSize(), lldb::eByteOrderBig, 8);
81 my_extractor.Dump(&ss, 0, lldb::eFormatBytesWithASCII, 1, my_buffer.GetByteSize(), 32, allocation_process_addr, 0, 0);
83 log->PutCString(ss.GetData());
87 return allocation_process_addr;
91 IRExecutionUnit::FreeNow (lldb::addr_t allocation)
93 if (allocation == LLDB_INVALID_ADDRESS)
98 Free(allocation, err);
102 IRExecutionUnit::DisassembleFunction (Stream &stream,
103 lldb::ProcessSP &process_wp)
105 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
107 ExecutionContext exe_ctx(process_wp);
113 lldb::addr_t func_local_addr = LLDB_INVALID_ADDRESS;
114 lldb::addr_t func_remote_addr = LLDB_INVALID_ADDRESS;
116 for (JittedFunction &function : m_jitted_functions)
118 if (strstr(function.m_name.c_str(), m_name.AsCString()))
120 func_local_addr = function.m_local_addr;
121 func_remote_addr = function.m_remote_addr;
125 if (func_local_addr == LLDB_INVALID_ADDRESS)
127 ret.SetErrorToGenericError();
128 ret.SetErrorStringWithFormat("Couldn't find function %s for disassembly", m_name.AsCString());
133 log->Printf("Found function, has local address 0x%" PRIx64 " and remote address 0x%" PRIx64, (uint64_t)func_local_addr, (uint64_t)func_remote_addr);
135 std::pair <lldb::addr_t, lldb::addr_t> func_range;
137 func_range = GetRemoteRangeForLocal(func_local_addr);
139 if (func_range.first == 0 && func_range.second == 0)
141 ret.SetErrorToGenericError();
142 ret.SetErrorStringWithFormat("Couldn't find code range for function %s", m_name.AsCString());
147 log->Printf("Function's code range is [0x%" PRIx64 "+0x%" PRIx64 "]", func_range.first, func_range.second);
149 Target *target = exe_ctx.GetTargetPtr();
152 ret.SetErrorToGenericError();
153 ret.SetErrorString("Couldn't find the target");
157 lldb::DataBufferSP buffer_sp(new DataBufferHeap(func_range.second, 0));
159 Process *process = exe_ctx.GetProcessPtr();
161 process->ReadMemory(func_remote_addr, buffer_sp->GetBytes(), buffer_sp->GetByteSize(), err);
165 ret.SetErrorToGenericError();
166 ret.SetErrorStringWithFormat("Couldn't read from process: %s", err.AsCString("unknown error"));
170 ArchSpec arch(target->GetArchitecture());
172 const char *plugin_name = NULL;
173 const char *flavor_string = NULL;
174 lldb::DisassemblerSP disassembler_sp = Disassembler::FindPlugin(arch, flavor_string, plugin_name);
176 if (!disassembler_sp)
178 ret.SetErrorToGenericError();
179 ret.SetErrorStringWithFormat("Unable to find disassembler plug-in for %s architecture.", arch.GetArchitectureName());
185 ret.SetErrorToGenericError();
186 ret.SetErrorString("Couldn't find the process");
190 DataExtractor extractor(buffer_sp,
191 process->GetByteOrder(),
192 target->GetArchitecture().GetAddressByteSize());
196 log->Printf("Function data has contents:");
197 extractor.PutToLog (log,
199 extractor.GetByteSize(),
202 DataExtractor::TypeUInt8);
205 disassembler_sp->DecodeInstructions (Address (func_remote_addr), extractor, 0, UINT32_MAX, false, false);
207 InstructionList &instruction_list = disassembler_sp->GetInstructionList();
208 const uint32_t max_opcode_byte_size = instruction_list.GetMaxOpcocdeByteSize();
210 for (size_t instruction_index = 0, num_instructions = instruction_list.GetSize();
211 instruction_index < num_instructions;
214 Instruction *instruction = instruction_list.GetInstructionAtIndex(instruction_index).get();
215 instruction->Dump (&stream,
216 max_opcode_byte_size,
220 stream.PutChar('\n');
222 // FIXME: The DisassemblerLLVMC has a reference cycle and won't go away if it has any active instructions.
223 // I'll fix that but for now, just clear the list and it will go away nicely.
224 disassembler_sp->GetInstructionList().Clear();
228 static void ReportInlineAsmError(const llvm::SMDiagnostic &diagnostic, void *Context, unsigned LocCookie)
230 Error *err = static_cast<Error*>(Context);
232 if (err && err->Success())
234 err->SetErrorToGenericError();
235 err->SetErrorStringWithFormat("Inline assembly error: %s", diagnostic.getMessage().str().c_str());
240 IRExecutionUnit::GetRunnableInfo(Error &error,
241 lldb::addr_t &func_addr,
242 lldb::addr_t &func_end)
244 lldb::ProcessSP process_sp(GetProcessWP().lock());
246 func_addr = LLDB_INVALID_ADDRESS;
247 func_end = LLDB_INVALID_ADDRESS;
251 error.SetErrorToGenericError();
252 error.SetErrorString("Couldn't write the JIT compiled code into the process because the process is invalid");
258 func_addr = m_function_load_addr;
259 func_end = m_function_end_load_addr;
266 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
268 std::string error_string;
273 llvm::raw_string_ostream oss(s);
275 m_module->print(oss, NULL);
279 log->Printf ("Module being sent to JIT: \n%s", s.c_str());
282 llvm::Triple triple(m_module->getTargetTriple());
283 llvm::Function *function = m_module->getFunction (m_name.AsCString());
284 llvm::Reloc::Model relocModel;
285 llvm::CodeModel::Model codeModel;
287 if (triple.isOSBinFormatELF())
289 relocModel = llvm::Reloc::Static;
290 // This will be small for 32-bit and large for 64-bit.
291 codeModel = llvm::CodeModel::JITDefault;
295 relocModel = llvm::Reloc::PIC_;
296 codeModel = llvm::CodeModel::Small;
299 m_module_ap->getContext().setInlineAsmDiagnosticHandler(ReportInlineAsmError, &error);
301 llvm::EngineBuilder builder(m_module_ap.get());
303 builder.setEngineKind(llvm::EngineKind::JIT)
304 .setErrorStr(&error_string)
305 .setRelocationModel(relocModel)
306 .setJITMemoryManager(new MemoryManager(*this))
307 .setOptLevel(llvm::CodeGenOpt::Less)
308 .setAllocateGVsWithCode(true)
309 .setCodeModel(codeModel)
312 llvm::StringRef mArch;
313 llvm::StringRef mCPU;
314 llvm::SmallVector<std::string, 0> mAttrs;
316 for (std::string &feature : m_cpu_features)
317 mAttrs.push_back(feature);
319 llvm::TargetMachine *target_machine = builder.selectTarget(triple,
324 m_execution_engine_ap.reset(builder.create(target_machine));
326 if (!m_execution_engine_ap.get())
328 error.SetErrorToGenericError();
329 error.SetErrorStringWithFormat("Couldn't JIT the function: %s", error_string.c_str());
334 m_module_ap.release(); // ownership was transferred
337 m_execution_engine_ap->DisableLazyCompilation();
339 // We don't actually need the function pointer here, this just forces it to get resolved.
341 void *fun_ptr = m_execution_engine_ap->getPointerToFunction(function);
343 if (!error.Success())
345 // We got an error through our callback!
351 error.SetErrorToGenericError();
352 error.SetErrorStringWithFormat("Couldn't find '%s' in the JITted module", m_name.AsCString());
358 error.SetErrorToGenericError();
359 error.SetErrorStringWithFormat("'%s' was in the JITted module but wasn't lowered", m_name.AsCString());
363 m_jitted_functions.push_back (JittedFunction(m_name.AsCString(), (lldb::addr_t)fun_ptr));
365 CommitAllocations(process_sp);
366 ReportAllocations(*m_execution_engine_ap);
367 WriteData(process_sp);
369 for (JittedFunction &jitted_function : m_jitted_functions)
371 jitted_function.m_remote_addr = GetRemoteAddressForLocal (jitted_function.m_local_addr);
373 if (!jitted_function.m_name.compare(m_name.AsCString()))
375 AddrRange func_range = GetRemoteRangeForLocal(jitted_function.m_local_addr);
376 m_function_end_load_addr = func_range.first + func_range.second;
377 m_function_load_addr = jitted_function.m_remote_addr;
383 log->Printf("Code can be run in the target.");
385 StreamString disassembly_stream;
387 Error err = DisassembleFunction(disassembly_stream, process_sp);
391 log->Printf("Couldn't disassemble function : %s", err.AsCString("unknown error"));
395 log->Printf("Function disassembly:\n%s", disassembly_stream.GetData());
399 func_addr = m_function_load_addr;
400 func_end = m_function_end_load_addr;
405 IRExecutionUnit::~IRExecutionUnit ()
408 m_execution_engine_ap.reset();
409 m_context_ap.reset();
412 IRExecutionUnit::MemoryManager::MemoryManager (IRExecutionUnit &parent) :
413 m_default_mm_ap (llvm::JITMemoryManager::CreateDefaultMemManager()),
419 IRExecutionUnit::MemoryManager::setMemoryWritable ()
421 m_default_mm_ap->setMemoryWritable();
425 IRExecutionUnit::MemoryManager::setMemoryExecutable ()
427 m_default_mm_ap->setMemoryExecutable();
432 IRExecutionUnit::MemoryManager::startFunctionBody(const llvm::Function *F,
433 uintptr_t &ActualSize)
435 return m_default_mm_ap->startFunctionBody(F, ActualSize);
439 IRExecutionUnit::MemoryManager::allocateStub(const llvm::GlobalValue* F,
443 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
445 uint8_t *return_value = m_default_mm_ap->allocateStub(F, StubSize, Alignment);
447 m_parent.m_records.push_back(AllocationRecord((uintptr_t)return_value,
448 lldb::ePermissionsReadable | lldb::ePermissionsWritable,
454 log->Printf("IRExecutionUnit::allocateStub (F=%p, StubSize=%u, Alignment=%u) = %p",
455 F, StubSize, Alignment, return_value);
462 IRExecutionUnit::MemoryManager::endFunctionBody(const llvm::Function *F,
463 uint8_t *FunctionStart,
464 uint8_t *FunctionEnd)
466 m_default_mm_ap->endFunctionBody(F, FunctionStart, FunctionEnd);
470 IRExecutionUnit::MemoryManager::allocateSpace(intptr_t Size, unsigned Alignment)
472 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
474 uint8_t *return_value = m_default_mm_ap->allocateSpace(Size, Alignment);
476 m_parent.m_records.push_back(AllocationRecord((uintptr_t)return_value,
477 lldb::ePermissionsReadable | lldb::ePermissionsWritable,
483 log->Printf("IRExecutionUnit::allocateSpace(Size=%" PRIu64 ", Alignment=%u) = %p",
484 (uint64_t)Size, Alignment, return_value);
491 IRExecutionUnit::MemoryManager::allocateCodeSection(uintptr_t Size,
495 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
497 uint8_t *return_value = m_default_mm_ap->allocateCodeSection(Size, Alignment, SectionID);
499 m_parent.m_records.push_back(AllocationRecord((uintptr_t)return_value,
500 lldb::ePermissionsReadable | lldb::ePermissionsExecutable,
507 log->Printf("IRExecutionUnit::allocateCodeSection(Size=0x%" PRIx64 ", Alignment=%u, SectionID=%u) = %p",
508 (uint64_t)Size, Alignment, SectionID, return_value);
515 IRExecutionUnit::MemoryManager::allocateDataSection(uintptr_t Size,
520 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
522 uint8_t *return_value = m_default_mm_ap->allocateDataSection(Size, Alignment, SectionID, IsReadOnly);
524 m_parent.m_records.push_back(AllocationRecord((uintptr_t)return_value,
525 lldb::ePermissionsReadable | lldb::ePermissionsWritable,
531 log->Printf("IRExecutionUnit::allocateDataSection(Size=0x%" PRIx64 ", Alignment=%u, SectionID=%u) = %p",
532 (uint64_t)Size, Alignment, SectionID, return_value);
539 IRExecutionUnit::MemoryManager::allocateGlobal(uintptr_t Size,
542 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
544 uint8_t *return_value = m_default_mm_ap->allocateGlobal(Size, Alignment);
546 m_parent.m_records.push_back(AllocationRecord((uintptr_t)return_value,
547 lldb::ePermissionsReadable | lldb::ePermissionsWritable,
553 log->Printf("IRExecutionUnit::allocateGlobal(Size=0x%" PRIx64 ", Alignment=%u) = %p",
554 (uint64_t)Size, Alignment, return_value);
561 IRExecutionUnit::MemoryManager::deallocateFunctionBody(void *Body)
563 m_default_mm_ap->deallocateFunctionBody(Body);
567 IRExecutionUnit::MemoryManager::startExceptionTable(const llvm::Function* F,
568 uintptr_t &ActualSize)
570 return m_default_mm_ap->startExceptionTable(F, ActualSize);
574 IRExecutionUnit::MemoryManager::endExceptionTable(const llvm::Function *F,
577 uint8_t* FrameRegister)
579 m_default_mm_ap->endExceptionTable(F, TableStart, TableEnd, FrameRegister);
583 IRExecutionUnit::MemoryManager::deallocateExceptionTable(void *ET)
585 m_default_mm_ap->deallocateExceptionTable (ET);
589 IRExecutionUnit::GetRemoteAddressForLocal (lldb::addr_t local_address)
591 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
593 for (AllocationRecord &record : m_records)
595 if (local_address >= record.m_host_address &&
596 local_address < record.m_host_address + record.m_size)
598 if (record.m_process_address == LLDB_INVALID_ADDRESS)
599 return LLDB_INVALID_ADDRESS;
601 lldb::addr_t ret = record.m_process_address + (local_address - record.m_host_address);
605 log->Printf("IRExecutionUnit::GetRemoteAddressForLocal() found 0x%" PRIx64 " in [0x%" PRIx64 "..0x%" PRIx64 "], and returned 0x%" PRIx64 " from [0x%" PRIx64 "..0x%" PRIx64 "].",
607 (uint64_t)record.m_host_address,
608 (uint64_t)record.m_host_address + (uint64_t)record.m_size,
610 record.m_process_address,
611 record.m_process_address + record.m_size);
618 return LLDB_INVALID_ADDRESS;
621 IRExecutionUnit::AddrRange
622 IRExecutionUnit::GetRemoteRangeForLocal (lldb::addr_t local_address)
624 for (AllocationRecord &record : m_records)
626 if (local_address >= record.m_host_address &&
627 local_address < record.m_host_address + record.m_size)
629 if (record.m_process_address == LLDB_INVALID_ADDRESS)
630 return AddrRange(0, 0);
632 return AddrRange(record.m_process_address, record.m_size);
636 return AddrRange (0, 0);
640 IRExecutionUnit::CommitAllocations (lldb::ProcessSP &process_sp)
644 lldb_private::Error err;
646 for (AllocationRecord &record : m_records)
648 if (record.m_process_address != LLDB_INVALID_ADDRESS)
652 record.m_process_address = Malloc(record.m_size,
654 record.m_permissions,
655 eAllocationPolicyProcessOnly,
667 for (AllocationRecord &record : m_records)
669 if (record.m_process_address != LLDB_INVALID_ADDRESS)
671 Free(record.m_process_address, err);
672 record.m_process_address = LLDB_INVALID_ADDRESS;
681 IRExecutionUnit::ReportAllocations (llvm::ExecutionEngine &engine)
683 for (AllocationRecord &record : m_records)
685 if (record.m_process_address == LLDB_INVALID_ADDRESS)
688 if (record.m_section_id == eSectionIDInvalid)
691 engine.mapSectionAddress((void*)record.m_host_address, record.m_process_address);
694 // Trigger re-application of relocations.
695 engine.finalizeObject();
699 IRExecutionUnit::WriteData (lldb::ProcessSP &process_sp)
701 for (AllocationRecord &record : m_records)
703 if (record.m_process_address == LLDB_INVALID_ADDRESS)
706 lldb_private::Error err;
708 WriteMemory (record.m_process_address, (uint8_t*)record.m_host_address, record.m_size, err);
715 IRExecutionUnit::AllocationRecord::dump (Log *log)
720 log->Printf("[0x%llx+0x%llx]->0x%llx (alignment %d, section ID %d)",
721 (unsigned long long)m_host_address,
722 (unsigned long long)m_size,
723 (unsigned long long)m_process_address,
724 (unsigned)m_alignment,
725 (unsigned)m_section_id);