blob: efa149737ee00964812a2a3804c7c3a3b169fbaf [file] [log] [blame]
Sean Callanan5a1af4e2013-04-05 02:22:57 +00001//===-- IRExecutionUnit.cpp -------------------------------------*- C++ -*-===//
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002//
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
Sean Callanan8dfb68e2013-03-19 00:10:07 +000010#include "llvm/ExecutionEngine/ExecutionEngine.h"
Sean Callanan5deb06e2016-09-26 20:18:51 +000011#include "llvm/ExecutionEngine/ObjectCache.h"
Sean Callananbd4dc692016-03-21 22:23:38 +000012#include "llvm/IR/Constants.h"
Sean Callanan44bc6572013-03-27 03:09:55 +000013#include "llvm/IR/LLVMContext.h"
Sean Callanan8dfb68e2013-03-19 00:10:07 +000014#include "llvm/IR/Module.h"
Sean Callanan44bc6572013-03-27 03:09:55 +000015#include "llvm/Support/SourceMgr.h"
Zachary Turnera78bd7f2015-03-03 23:11:11 +000016#include "llvm/Support/raw_ostream.h"
17
Jason Molendaaff1b352014-10-10 23:07:36 +000018#include "lldb/Core/Debugger.h"
Sean Callanan8dfb68e2013-03-19 00:10:07 +000019#include "lldb/Core/Disassembler.h"
Greg Clayton23f8c952014-03-24 23:10:19 +000020#include "lldb/Core/Module.h"
21#include "lldb/Core/Section.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000022#include "lldb/Expression/IRExecutionUnit.h"
Sean Callananb2814802016-02-12 21:11:25 +000023#include "lldb/Symbol/CompileUnit.h"
Zachary Turnera78bd7f2015-03-03 23:11:11 +000024#include "lldb/Symbol/SymbolContext.h"
Sean Callananb2814802016-02-12 21:11:25 +000025#include "lldb/Symbol/SymbolFile.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000026#include "lldb/Symbol/SymbolVendor.h"
Sean Callanan8dfb68e2013-03-19 00:10:07 +000027#include "lldb/Target/ExecutionContext.h"
Zachary Turnera78bd7f2015-03-03 23:11:11 +000028#include "lldb/Target/ObjCLanguageRuntime.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000029#include "lldb/Target/Target.h"
Zachary Turner666cc0b2017-03-04 01:30:05 +000030#include "lldb/Utility/DataBufferHeap.h"
31#include "lldb/Utility/DataExtractor.h"
Sean Callananbd4dc692016-03-21 22:23:38 +000032#include "lldb/Utility/LLDBAssert.h"
Zachary Turner6f9e6902017-03-03 20:56:28 +000033#include "lldb/Utility/Log.h"
Sean Callanan8dfb68e2013-03-19 00:10:07 +000034
Sean Callananb2814802016-02-12 21:11:25 +000035#include "lldb/../../source/Plugins/Language/CPlusPlus/CPlusPlusLanguage.h"
Zachary Turner8e8d4b92018-05-23 23:56:09 +000036#include "lldb/../../source/Plugins/ObjectFile/JIT/ObjectFileJIT.h"
Sean Callananb2814802016-02-12 21:11:25 +000037
Sean Callanan8dfb68e2013-03-19 00:10:07 +000038using namespace lldb_private;
39
Kate Stoneb9c1b512016-09-06 20:57:50 +000040IRExecutionUnit::IRExecutionUnit(std::unique_ptr<llvm::LLVMContext> &context_ap,
41 std::unique_ptr<llvm::Module> &module_ap,
42 ConstString &name,
43 const lldb::TargetSP &target_sp,
44 const SymbolContext &sym_ctx,
45 std::vector<std::string> &cpu_features)
46 : IRMemoryMap(target_sp), m_context_ap(context_ap.release()),
47 m_module_ap(module_ap.release()), m_module(m_module_ap.get()),
48 m_cpu_features(cpu_features), m_name(name), m_sym_ctx(sym_ctx),
49 m_did_jit(false), m_function_load_addr(LLDB_INVALID_ADDRESS),
50 m_function_end_load_addr(LLDB_INVALID_ADDRESS),
51 m_reported_allocations(false) {}
Sean Callanan8dfb68e2013-03-19 00:10:07 +000052
Kate Stoneb9c1b512016-09-06 20:57:50 +000053lldb::addr_t IRExecutionUnit::WriteNow(const uint8_t *bytes, size_t size,
Zachary Turner97206d52017-05-12 04:51:55 +000054 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +000055 const bool zero_memory = false;
56 lldb::addr_t allocation_process_addr =
57 Malloc(size, 8, lldb::ePermissionsWritable | lldb::ePermissionsReadable,
58 eAllocationPolicyMirror, zero_memory, error);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +000059
Kate Stoneb9c1b512016-09-06 20:57:50 +000060 if (!error.Success())
61 return LLDB_INVALID_ADDRESS;
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +000062
Kate Stoneb9c1b512016-09-06 20:57:50 +000063 WriteMemory(allocation_process_addr, bytes, size, error);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +000064
Kate Stoneb9c1b512016-09-06 20:57:50 +000065 if (!error.Success()) {
Zachary Turner97206d52017-05-12 04:51:55 +000066 Status err;
Kate Stoneb9c1b512016-09-06 20:57:50 +000067 Free(allocation_process_addr, err);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +000068
Kate Stoneb9c1b512016-09-06 20:57:50 +000069 return LLDB_INVALID_ADDRESS;
70 }
Sean Callanan8dfb68e2013-03-19 00:10:07 +000071
Kate Stoneb9c1b512016-09-06 20:57:50 +000072 if (Log *log =
73 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)) {
74 DataBufferHeap my_buffer(size, 0);
Zachary Turner97206d52017-05-12 04:51:55 +000075 Status err;
Kate Stoneb9c1b512016-09-06 20:57:50 +000076 ReadMemory(my_buffer.GetBytes(), allocation_process_addr, size, err);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +000077
Kate Stoneb9c1b512016-09-06 20:57:50 +000078 if (err.Success()) {
79 DataExtractor my_extractor(my_buffer.GetBytes(), my_buffer.GetByteSize(),
80 lldb::eByteOrderBig, 8);
81 my_extractor.PutToLog(log, 0, my_buffer.GetByteSize(),
82 allocation_process_addr, 16,
Sean Callanan8dfb68e2013-03-19 00:10:07 +000083 DataExtractor::TypeUInt8);
84 }
Kate Stoneb9c1b512016-09-06 20:57:50 +000085 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +000086
Kate Stoneb9c1b512016-09-06 20:57:50 +000087 return allocation_process_addr;
88}
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +000089
Kate Stoneb9c1b512016-09-06 20:57:50 +000090void IRExecutionUnit::FreeNow(lldb::addr_t allocation) {
91 if (allocation == LLDB_INVALID_ADDRESS)
92 return;
93
Zachary Turner97206d52017-05-12 04:51:55 +000094 Status err;
Kate Stoneb9c1b512016-09-06 20:57:50 +000095
96 Free(allocation, err);
97}
98
Zachary Turner97206d52017-05-12 04:51:55 +000099Status IRExecutionUnit::DisassembleFunction(Stream &stream,
100 lldb::ProcessSP &process_wp) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000101 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
102
103 ExecutionContext exe_ctx(process_wp);
104
Zachary Turner97206d52017-05-12 04:51:55 +0000105 Status ret;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000106
107 ret.Clear();
108
109 lldb::addr_t func_local_addr = LLDB_INVALID_ADDRESS;
110 lldb::addr_t func_remote_addr = LLDB_INVALID_ADDRESS;
111
112 for (JittedFunction &function : m_jitted_functions) {
113 if (function.m_name == m_name) {
114 func_local_addr = function.m_local_addr;
115 func_remote_addr = function.m_remote_addr;
116 }
117 }
118
119 if (func_local_addr == LLDB_INVALID_ADDRESS) {
120 ret.SetErrorToGenericError();
121 ret.SetErrorStringWithFormat("Couldn't find function %s for disassembly",
122 m_name.AsCString());
Sean Callanan8dfb68e2013-03-19 00:10:07 +0000123 return ret;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000124 }
125
126 if (log)
127 log->Printf("Found function, has local address 0x%" PRIx64
128 " and remote address 0x%" PRIx64,
129 (uint64_t)func_local_addr, (uint64_t)func_remote_addr);
130
131 std::pair<lldb::addr_t, lldb::addr_t> func_range;
132
133 func_range = GetRemoteRangeForLocal(func_local_addr);
134
135 if (func_range.first == 0 && func_range.second == 0) {
136 ret.SetErrorToGenericError();
137 ret.SetErrorStringWithFormat("Couldn't find code range for function %s",
138 m_name.AsCString());
139 return ret;
140 }
141
142 if (log)
143 log->Printf("Function's code range is [0x%" PRIx64 "+0x%" PRIx64 "]",
144 func_range.first, func_range.second);
145
146 Target *target = exe_ctx.GetTargetPtr();
147 if (!target) {
148 ret.SetErrorToGenericError();
149 ret.SetErrorString("Couldn't find the target");
150 return ret;
151 }
152
153 lldb::DataBufferSP buffer_sp(new DataBufferHeap(func_range.second, 0));
154
155 Process *process = exe_ctx.GetProcessPtr();
Zachary Turner97206d52017-05-12 04:51:55 +0000156 Status err;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000157 process->ReadMemory(func_remote_addr, buffer_sp->GetBytes(),
158 buffer_sp->GetByteSize(), err);
159
160 if (!err.Success()) {
161 ret.SetErrorToGenericError();
162 ret.SetErrorStringWithFormat("Couldn't read from process: %s",
163 err.AsCString("unknown error"));
164 return ret;
165 }
166
167 ArchSpec arch(target->GetArchitecture());
168
169 const char *plugin_name = NULL;
170 const char *flavor_string = NULL;
171 lldb::DisassemblerSP disassembler_sp =
172 Disassembler::FindPlugin(arch, flavor_string, plugin_name);
173
174 if (!disassembler_sp) {
175 ret.SetErrorToGenericError();
176 ret.SetErrorStringWithFormat(
177 "Unable to find disassembler plug-in for %s architecture.",
178 arch.GetArchitectureName());
179 return ret;
180 }
181
182 if (!process) {
183 ret.SetErrorToGenericError();
184 ret.SetErrorString("Couldn't find the process");
185 return ret;
186 }
187
188 DataExtractor extractor(buffer_sp, process->GetByteOrder(),
189 target->GetArchitecture().GetAddressByteSize());
190
191 if (log) {
192 log->Printf("Function data has contents:");
193 extractor.PutToLog(log, 0, extractor.GetByteSize(), func_remote_addr, 16,
194 DataExtractor::TypeUInt8);
195 }
196
197 disassembler_sp->DecodeInstructions(Address(func_remote_addr), extractor, 0,
198 UINT32_MAX, false, false);
199
200 InstructionList &instruction_list = disassembler_sp->GetInstructionList();
201 instruction_list.Dump(&stream, true, true, &exe_ctx);
202 return ret;
Sean Callanan8dfb68e2013-03-19 00:10:07 +0000203}
204
Kate Stoneb9c1b512016-09-06 20:57:50 +0000205static void ReportInlineAsmError(const llvm::SMDiagnostic &diagnostic,
206 void *Context, unsigned LocCookie) {
Zachary Turner97206d52017-05-12 04:51:55 +0000207 Status *err = static_cast<Status *>(Context);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000208
Kate Stoneb9c1b512016-09-06 20:57:50 +0000209 if (err && err->Success()) {
210 err->SetErrorToGenericError();
211 err->SetErrorStringWithFormat("Inline assembly error: %s",
212 diagnostic.getMessage().str().c_str());
213 }
Sean Callanan44bc6572013-03-27 03:09:55 +0000214}
215
Kate Stoneb9c1b512016-09-06 20:57:50 +0000216void IRExecutionUnit::ReportSymbolLookupError(const ConstString &name) {
217 m_failed_lookups.push_back(name);
Jim Ingham27e5fe82015-01-27 18:03:05 +0000218}
219
Zachary Turner97206d52017-05-12 04:51:55 +0000220void IRExecutionUnit::GetRunnableInfo(Status &error, lldb::addr_t &func_addr,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000221 lldb::addr_t &func_end) {
222 lldb::ProcessSP process_sp(GetProcessWP().lock());
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000223
Kate Stoneb9c1b512016-09-06 20:57:50 +0000224 static std::recursive_mutex s_runnable_info_mutex;
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000225
Kate Stoneb9c1b512016-09-06 20:57:50 +0000226 func_addr = LLDB_INVALID_ADDRESS;
227 func_end = LLDB_INVALID_ADDRESS;
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000228
Kate Stoneb9c1b512016-09-06 20:57:50 +0000229 if (!process_sp) {
230 error.SetErrorToGenericError();
231 error.SetErrorString("Couldn't write the JIT compiled code into the "
232 "process because the process is invalid");
233 return;
234 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000235
Kate Stoneb9c1b512016-09-06 20:57:50 +0000236 if (m_did_jit) {
Sean Callanan5a1af4e2013-04-05 02:22:57 +0000237 func_addr = m_function_load_addr;
238 func_end = m_function_end_load_addr;
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000239
Sean Callanan5a1af4e2013-04-05 02:22:57 +0000240 return;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000241 };
Sean Callanan8dfb68e2013-03-19 00:10:07 +0000242
Kate Stoneb9c1b512016-09-06 20:57:50 +0000243 std::lock_guard<std::recursive_mutex> guard(s_runnable_info_mutex);
Sean Callanan8dfb68e2013-03-19 00:10:07 +0000244
Kate Stoneb9c1b512016-09-06 20:57:50 +0000245 m_did_jit = true;
Sean Callanan8dfb68e2013-03-19 00:10:07 +0000246
Kate Stoneb9c1b512016-09-06 20:57:50 +0000247 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan8dfb68e2013-03-19 00:10:07 +0000248
Kate Stoneb9c1b512016-09-06 20:57:50 +0000249 std::string error_string;
250
251 if (log) {
252 std::string s;
253 llvm::raw_string_ostream oss(s);
254
255 m_module->print(oss, NULL);
256
257 oss.flush();
258
259 log->Printf("Module being sent to JIT: \n%s", s.c_str());
260 }
261
262 llvm::Triple triple(m_module->getTargetTriple());
263 llvm::Reloc::Model relocModel;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000264
265 if (triple.isOSBinFormatELF()) {
266 relocModel = llvm::Reloc::Static;
267 } else {
268 relocModel = llvm::Reloc::PIC_;
269 }
270
Kate Stoneb9c1b512016-09-06 20:57:50 +0000271 m_module_ap->getContext().setInlineAsmDiagnosticHandler(ReportInlineAsmError,
272 &error);
273
274 llvm::EngineBuilder builder(std::move(m_module_ap));
275
276 builder.setEngineKind(llvm::EngineKind::JIT)
277 .setErrorStr(&error_string)
278 .setRelocationModel(relocModel)
279 .setMCJITMemoryManager(
280 std::unique_ptr<MemoryManager>(new MemoryManager(*this)))
Pavel Labathd7396362017-11-13 14:03:17 +0000281 .setOptLevel(llvm::CodeGenOpt::Less);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000282
283 llvm::StringRef mArch;
284 llvm::StringRef mCPU;
285 llvm::SmallVector<std::string, 0> mAttrs;
286
287 for (std::string &feature : m_cpu_features)
288 mAttrs.push_back(feature);
289
290 llvm::TargetMachine *target_machine =
291 builder.selectTarget(triple, mArch, mCPU, mAttrs);
292
293 m_execution_engine_ap.reset(builder.create(target_machine));
294
295 m_strip_underscore =
296 (m_execution_engine_ap->getDataLayout().getGlobalPrefix() == '_');
297
298 if (!m_execution_engine_ap.get()) {
299 error.SetErrorToGenericError();
300 error.SetErrorStringWithFormat("Couldn't JIT the function: %s",
301 error_string.c_str());
302 return;
303 }
304
Sean Callanan5deb06e2016-09-26 20:18:51 +0000305 class ObjectDumper : public llvm::ObjectCache {
306 public:
307 void notifyObjectCompiled(const llvm::Module *module,
308 llvm::MemoryBufferRef object) override {
309 int fd = 0;
310 llvm::SmallVector<char, 256> result_path;
311 std::string object_name_model =
312 "jit-object-" + module->getModuleIdentifier() + "-%%%.o";
313 (void)llvm::sys::fs::createUniqueFile(object_name_model, fd, result_path);
314 llvm::raw_fd_ostream fds(fd, true);
315 fds.write(object.getBufferStart(), object.getBufferSize());
316 }
317
318 std::unique_ptr<llvm::MemoryBuffer>
319 getObject(const llvm::Module *module) override {
320 // Return nothing - we're just abusing the object-cache mechanism to dump
321 // objects.
322 return nullptr;
323 }
324 };
325
326 if (process_sp->GetTarget().GetEnableSaveObjects()) {
327 m_object_cache_ap = llvm::make_unique<ObjectDumper>();
328 m_execution_engine_ap->setObjectCache(m_object_cache_ap.get());
329 }
330
Kate Stoneb9c1b512016-09-06 20:57:50 +0000331 // Make sure we see all sections, including ones that don't have
332 // relocations...
333 m_execution_engine_ap->setProcessAllSections(true);
334
335 m_execution_engine_ap->DisableLazyCompilation();
336
337 for (llvm::Function &function : *m_module) {
338 if (function.isDeclaration() || function.hasPrivateLinkage())
339 continue;
340
341 const bool external =
342 function.hasExternalLinkage() || function.hasLinkOnceODRLinkage();
343
344 void *fun_ptr = m_execution_engine_ap->getPointerToFunction(&function);
345
346 if (!error.Success()) {
347 // We got an error through our callback!
348 return;
Greg Clayton23f8c952014-03-24 23:10:19 +0000349 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000350
Kate Stoneb9c1b512016-09-06 20:57:50 +0000351 if (!fun_ptr) {
352 error.SetErrorToGenericError();
353 error.SetErrorStringWithFormat(
354 "'%s' was in the JITted module but wasn't lowered",
355 function.getName().str().c_str());
356 return;
357 }
358 m_jitted_functions.push_back(JittedFunction(
359 function.getName().str().c_str(), external, (lldb::addr_t)fun_ptr));
360 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000361
Kate Stoneb9c1b512016-09-06 20:57:50 +0000362 CommitAllocations(process_sp);
363 ReportAllocations(*m_execution_engine_ap);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000364
Kate Stoneb9c1b512016-09-06 20:57:50 +0000365 // We have to do this after calling ReportAllocations because for the MCJIT,
Adrian Prantl05097242018-04-30 16:49:04 +0000366 // getGlobalValueAddress will cause the JIT to perform all relocations. That
367 // can only be done once, and has to happen after we do the remapping from
368 // local -> remote. That means we don't know the local address of the
369 // Variables, but we don't need that for anything, so that's okay.
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000370
Kate Stoneb9c1b512016-09-06 20:57:50 +0000371 std::function<void(llvm::GlobalValue &)> RegisterOneValue = [this](
372 llvm::GlobalValue &val) {
373 if (val.hasExternalLinkage() && !val.isDeclaration()) {
374 uint64_t var_ptr_addr =
375 m_execution_engine_ap->getGlobalValueAddress(val.getName().str());
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000376
Kate Stoneb9c1b512016-09-06 20:57:50 +0000377 lldb::addr_t remote_addr = GetRemoteAddressForLocal(var_ptr_addr);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000378
Kate Stoneb9c1b512016-09-06 20:57:50 +0000379 // This is a really unfortunae API that sometimes returns local addresses
Adrian Prantl05097242018-04-30 16:49:04 +0000380 // and sometimes returns remote addresses, based on whether the variable
381 // was relocated during ReportAllocations or not.
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000382
Kate Stoneb9c1b512016-09-06 20:57:50 +0000383 if (remote_addr == LLDB_INVALID_ADDRESS) {
384 remote_addr = var_ptr_addr;
385 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000386
Kate Stoneb9c1b512016-09-06 20:57:50 +0000387 if (var_ptr_addr != 0)
388 m_jitted_global_variables.push_back(JittedGlobalVariable(
389 val.getName().str().c_str(), LLDB_INVALID_ADDRESS, remote_addr));
390 }
391 };
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000392
Kate Stoneb9c1b512016-09-06 20:57:50 +0000393 for (llvm::GlobalVariable &global_var : m_module->getGlobalList()) {
394 RegisterOneValue(global_var);
395 }
396
397 for (llvm::GlobalAlias &global_alias : m_module->getAliasList()) {
398 RegisterOneValue(global_alias);
399 }
400
401 WriteData(process_sp);
402
403 if (m_failed_lookups.size()) {
404 StreamString ss;
405
406 ss.PutCString("Couldn't lookup symbols:\n");
407
408 bool emitNewLine = false;
409
410 for (const ConstString &failed_lookup : m_failed_lookups) {
411 if (emitNewLine)
412 ss.PutCString("\n");
413 emitNewLine = true;
414 ss.PutCString(" ");
415 ss.PutCString(Mangled(failed_lookup)
416 .GetDemangledName(lldb::eLanguageTypeObjC_plus_plus)
417 .AsCString());
418 }
419
420 m_failed_lookups.clear();
421
Zachary Turnerc1564272016-11-16 21:15:24 +0000422 error.SetErrorString(ss.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000423
424 return;
425 }
426
427 m_function_load_addr = LLDB_INVALID_ADDRESS;
428 m_function_end_load_addr = LLDB_INVALID_ADDRESS;
429
430 for (JittedFunction &jitted_function : m_jitted_functions) {
431 jitted_function.m_remote_addr =
432 GetRemoteAddressForLocal(jitted_function.m_local_addr);
433
434 if (!m_name.IsEmpty() && jitted_function.m_name == m_name) {
435 AddrRange func_range =
436 GetRemoteRangeForLocal(jitted_function.m_local_addr);
437 m_function_end_load_addr = func_range.first + func_range.second;
438 m_function_load_addr = jitted_function.m_remote_addr;
439 }
440 }
441
442 if (log) {
443 log->Printf("Code can be run in the target.");
444
445 StreamString disassembly_stream;
446
Zachary Turner97206d52017-05-12 04:51:55 +0000447 Status err = DisassembleFunction(disassembly_stream, process_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000448
449 if (!err.Success()) {
450 log->Printf("Couldn't disassemble function : %s",
451 err.AsCString("unknown error"));
452 } else {
453 log->Printf("Function disassembly:\n%s", disassembly_stream.GetData());
454 }
455
456 log->Printf("Sections: ");
457 for (AllocationRecord &record : m_records) {
458 if (record.m_process_address != LLDB_INVALID_ADDRESS) {
459 record.dump(log);
460
461 DataBufferHeap my_buffer(record.m_size, 0);
Zachary Turner97206d52017-05-12 04:51:55 +0000462 Status err;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000463 ReadMemory(my_buffer.GetBytes(), record.m_process_address,
464 record.m_size, err);
465
466 if (err.Success()) {
467 DataExtractor my_extractor(my_buffer.GetBytes(),
468 my_buffer.GetByteSize(),
469 lldb::eByteOrderBig, 8);
470 my_extractor.PutToLog(log, 0, my_buffer.GetByteSize(),
471 record.m_process_address, 16,
472 DataExtractor::TypeUInt8);
Greg Clayton23f8c952014-03-24 23:10:19 +0000473 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000474 } else {
475 record.dump(log);
476
477 DataExtractor my_extractor((const void *)record.m_host_address,
478 record.m_size, lldb::eByteOrderBig, 8);
479 my_extractor.PutToLog(log, 0, record.m_size, record.m_host_address, 16,
480 DataExtractor::TypeUInt8);
481 }
482 }
483 }
484
485 func_addr = m_function_load_addr;
486 func_end = m_function_end_load_addr;
487
488 return;
489}
490
491IRExecutionUnit::~IRExecutionUnit() {
492 m_module_ap.reset();
493 m_execution_engine_ap.reset();
494 m_context_ap.reset();
495}
496
497IRExecutionUnit::MemoryManager::MemoryManager(IRExecutionUnit &parent)
498 : m_default_mm_ap(new llvm::SectionMemoryManager()), m_parent(parent) {}
499
500IRExecutionUnit::MemoryManager::~MemoryManager() {}
501
502lldb::SectionType IRExecutionUnit::GetSectionTypeFromSectionName(
503 const llvm::StringRef &name, IRExecutionUnit::AllocationKind alloc_kind) {
504 lldb::SectionType sect_type = lldb::eSectionTypeCode;
505 switch (alloc_kind) {
506 case AllocationKind::Stub:
507 sect_type = lldb::eSectionTypeCode;
508 break;
509 case AllocationKind::Code:
510 sect_type = lldb::eSectionTypeCode;
511 break;
512 case AllocationKind::Data:
513 sect_type = lldb::eSectionTypeData;
514 break;
515 case AllocationKind::Global:
516 sect_type = lldb::eSectionTypeData;
517 break;
518 case AllocationKind::Bytes:
519 sect_type = lldb::eSectionTypeOther;
520 break;
521 }
522
523 if (!name.empty()) {
524 if (name.equals("__text") || name.equals(".text"))
525 sect_type = lldb::eSectionTypeCode;
526 else if (name.equals("__data") || name.equals(".data"))
527 sect_type = lldb::eSectionTypeCode;
528 else if (name.startswith("__debug_") || name.startswith(".debug_")) {
529 const uint32_t name_idx = name[0] == '_' ? 8 : 7;
530 llvm::StringRef dwarf_name(name.substr(name_idx));
531 switch (dwarf_name[0]) {
532 case 'a':
533 if (dwarf_name.equals("abbrev"))
534 sect_type = lldb::eSectionTypeDWARFDebugAbbrev;
535 else if (dwarf_name.equals("aranges"))
536 sect_type = lldb::eSectionTypeDWARFDebugAranges;
537 else if (dwarf_name.equals("addr"))
538 sect_type = lldb::eSectionTypeDWARFDebugAddr;
539 break;
540
541 case 'f':
542 if (dwarf_name.equals("frame"))
543 sect_type = lldb::eSectionTypeDWARFDebugFrame;
544 break;
545
546 case 'i':
547 if (dwarf_name.equals("info"))
548 sect_type = lldb::eSectionTypeDWARFDebugInfo;
549 break;
550
551 case 'l':
552 if (dwarf_name.equals("line"))
553 sect_type = lldb::eSectionTypeDWARFDebugLine;
554 else if (dwarf_name.equals("loc"))
555 sect_type = lldb::eSectionTypeDWARFDebugLoc;
George Rimare4dee262018-10-23 09:46:15 +0000556 else if (dwarf_name.equals("loclists"))
557 sect_type = lldb::eSectionTypeDWARFDebugLocLists;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000558 break;
559
560 case 'm':
561 if (dwarf_name.equals("macinfo"))
562 sect_type = lldb::eSectionTypeDWARFDebugMacInfo;
563 break;
564
565 case 'p':
566 if (dwarf_name.equals("pubnames"))
567 sect_type = lldb::eSectionTypeDWARFDebugPubNames;
568 else if (dwarf_name.equals("pubtypes"))
569 sect_type = lldb::eSectionTypeDWARFDebugPubTypes;
570 break;
571
572 case 's':
573 if (dwarf_name.equals("str"))
574 sect_type = lldb::eSectionTypeDWARFDebugStr;
575 else if (dwarf_name.equals("str_offsets"))
576 sect_type = lldb::eSectionTypeDWARFDebugStrOffsets;
577 break;
578
579 case 'r':
580 if (dwarf_name.equals("ranges"))
581 sect_type = lldb::eSectionTypeDWARFDebugRanges;
582 break;
583
584 default:
585 break;
586 }
Davide Italiano45925d72018-01-04 23:37:18 +0000587 } else if (name.startswith("__apple_") || name.startswith(".apple_"))
Kate Stoneb9c1b512016-09-06 20:57:50 +0000588 sect_type = lldb::eSectionTypeInvalid;
Davide Italiano45925d72018-01-04 23:37:18 +0000589 else if (name.equals("__objc_imageinfo"))
Kate Stoneb9c1b512016-09-06 20:57:50 +0000590 sect_type = lldb::eSectionTypeOther;
591 }
592 return sect_type;
Greg Clayton23f8c952014-03-24 23:10:19 +0000593}
594
Kate Stoneb9c1b512016-09-06 20:57:50 +0000595uint8_t *IRExecutionUnit::MemoryManager::allocateCodeSection(
596 uintptr_t Size, unsigned Alignment, unsigned SectionID,
597 llvm::StringRef SectionName) {
598 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000599
Kate Stoneb9c1b512016-09-06 20:57:50 +0000600 uint8_t *return_value = m_default_mm_ap->allocateCodeSection(
601 Size, Alignment, SectionID, SectionName);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000602
Kate Stoneb9c1b512016-09-06 20:57:50 +0000603 m_parent.m_records.push_back(AllocationRecord(
604 (uintptr_t)return_value,
605 lldb::ePermissionsReadable | lldb::ePermissionsExecutable,
606 GetSectionTypeFromSectionName(SectionName, AllocationKind::Code), Size,
607 Alignment, SectionID, SectionName.str().c_str()));
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000608
Kate Stoneb9c1b512016-09-06 20:57:50 +0000609 if (log) {
610 log->Printf("IRExecutionUnit::allocateCodeSection(Size=0x%" PRIx64
611 ", Alignment=%u, SectionID=%u) = %p",
612 (uint64_t)Size, Alignment, SectionID, (void *)return_value);
613 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000614
Kate Stoneb9c1b512016-09-06 20:57:50 +0000615 if (m_parent.m_reported_allocations) {
Zachary Turner97206d52017-05-12 04:51:55 +0000616 Status err;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000617 lldb::ProcessSP process_sp =
618 m_parent.GetBestExecutionContextScope()->CalculateProcess();
619
620 m_parent.CommitOneAllocation(process_sp, err, m_parent.m_records.back());
621 }
622
623 return return_value;
Sean Callanan8dfb68e2013-03-19 00:10:07 +0000624}
625
Kate Stoneb9c1b512016-09-06 20:57:50 +0000626uint8_t *IRExecutionUnit::MemoryManager::allocateDataSection(
627 uintptr_t Size, unsigned Alignment, unsigned SectionID,
628 llvm::StringRef SectionName, bool IsReadOnly) {
629 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan8dfb68e2013-03-19 00:10:07 +0000630
Kate Stoneb9c1b512016-09-06 20:57:50 +0000631 uint8_t *return_value = m_default_mm_ap->allocateDataSection(
632 Size, Alignment, SectionID, SectionName, IsReadOnly);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000633
Kate Stoneb9c1b512016-09-06 20:57:50 +0000634 uint32_t permissions = lldb::ePermissionsReadable;
635 if (!IsReadOnly)
636 permissions |= lldb::ePermissionsWritable;
637 m_parent.m_records.push_back(AllocationRecord(
638 (uintptr_t)return_value, permissions,
639 GetSectionTypeFromSectionName(SectionName, AllocationKind::Data), Size,
640 Alignment, SectionID, SectionName.str().c_str()));
641 if (log) {
642 log->Printf("IRExecutionUnit::allocateDataSection(Size=0x%" PRIx64
643 ", Alignment=%u, SectionID=%u) = %p",
644 (uint64_t)Size, Alignment, SectionID, (void *)return_value);
645 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000646
Kate Stoneb9c1b512016-09-06 20:57:50 +0000647 if (m_parent.m_reported_allocations) {
Zachary Turner97206d52017-05-12 04:51:55 +0000648 Status err;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000649 lldb::ProcessSP process_sp =
650 m_parent.GetBestExecutionContextScope()->CalculateProcess();
651
652 m_parent.CommitOneAllocation(process_sp, err, m_parent.m_records.back());
653 }
654
655 return return_value;
Sean Callanan8dfb68e2013-03-19 00:10:07 +0000656}
657
Sean Callananb2814802016-02-12 21:11:25 +0000658static ConstString
659FindBestAlternateMangledName(const ConstString &demangled,
660 const lldb::LanguageType &lang_type,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000661 const SymbolContext &sym_ctx) {
662 CPlusPlusLanguage::MethodName cpp_name(demangled);
663 std::string scope_qualified_name = cpp_name.GetScopeQualifiedName();
Sean Callananb2814802016-02-12 21:11:25 +0000664
Kate Stoneb9c1b512016-09-06 20:57:50 +0000665 if (!scope_qualified_name.size())
666 return ConstString();
Sean Callananb2814802016-02-12 21:11:25 +0000667
Kate Stoneb9c1b512016-09-06 20:57:50 +0000668 if (!sym_ctx.module_sp)
669 return ConstString();
Sean Callananb2814802016-02-12 21:11:25 +0000670
Kate Stoneb9c1b512016-09-06 20:57:50 +0000671 SymbolVendor *sym_vendor = sym_ctx.module_sp->GetSymbolVendor();
672 if (!sym_vendor)
673 return ConstString();
Sean Callananb2814802016-02-12 21:11:25 +0000674
Kate Stoneb9c1b512016-09-06 20:57:50 +0000675 lldb_private::SymbolFile *sym_file = sym_vendor->GetSymbolFile();
676 if (!sym_file)
677 return ConstString();
Sean Callananb2814802016-02-12 21:11:25 +0000678
Kate Stoneb9c1b512016-09-06 20:57:50 +0000679 std::vector<ConstString> alternates;
680 sym_file->GetMangledNamesForFunction(scope_qualified_name, alternates);
Sean Callananb2814802016-02-12 21:11:25 +0000681
Kate Stoneb9c1b512016-09-06 20:57:50 +0000682 std::vector<ConstString> param_and_qual_matches;
683 std::vector<ConstString> param_matches;
684 for (size_t i = 0; i < alternates.size(); i++) {
685 ConstString alternate_mangled_name = alternates[i];
686 Mangled mangled(alternate_mangled_name, true);
687 ConstString demangled = mangled.GetDemangledName(lang_type);
Sean Callananb2814802016-02-12 21:11:25 +0000688
Kate Stoneb9c1b512016-09-06 20:57:50 +0000689 CPlusPlusLanguage::MethodName alternate_cpp_name(demangled);
690 if (!cpp_name.IsValid())
691 continue;
Sean Callananb2814802016-02-12 21:11:25 +0000692
Kate Stoneb9c1b512016-09-06 20:57:50 +0000693 if (alternate_cpp_name.GetArguments() == cpp_name.GetArguments()) {
694 if (alternate_cpp_name.GetQualifiers() == cpp_name.GetQualifiers())
695 param_and_qual_matches.push_back(alternate_mangled_name);
696 else
697 param_matches.push_back(alternate_mangled_name);
Sean Callananb2814802016-02-12 21:11:25 +0000698 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000699 }
Sean Callananb2814802016-02-12 21:11:25 +0000700
Kate Stoneb9c1b512016-09-06 20:57:50 +0000701 if (param_and_qual_matches.size())
702 return param_and_qual_matches[0]; // It is assumed that there will be only
703 // one!
704 else if (param_matches.size())
705 return param_matches[0]; // Return one of them as a best match
706 else
707 return ConstString();
Sean Callananb2814802016-02-12 21:11:25 +0000708}
709
Kate Stoneb9c1b512016-09-06 20:57:50 +0000710struct IRExecutionUnit::SearchSpec {
711 ConstString name;
Zachary Turner117b1fa2018-10-25 20:45:40 +0000712 lldb::FunctionNameType mask;
Sean Callananb2814802016-02-12 21:11:25 +0000713
Zachary Turner117b1fa2018-10-25 20:45:40 +0000714 SearchSpec(ConstString n,
715 lldb::FunctionNameType m = lldb::eFunctionNameTypeFull)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000716 : name(n), mask(m) {}
Sean Callananb2814802016-02-12 21:11:25 +0000717};
718
Kate Stoneb9c1b512016-09-06 20:57:50 +0000719void IRExecutionUnit::CollectCandidateCNames(
720 std::vector<IRExecutionUnit::SearchSpec> &C_specs,
721 const ConstString &name) {
722 if (m_strip_underscore && name.AsCString()[0] == '_')
723 C_specs.insert(C_specs.begin(), ConstString(&name.AsCString()[1]));
724 C_specs.push_back(SearchSpec(name));
Sean Callananb2814802016-02-12 21:11:25 +0000725}
726
Kate Stoneb9c1b512016-09-06 20:57:50 +0000727void IRExecutionUnit::CollectCandidateCPlusPlusNames(
728 std::vector<IRExecutionUnit::SearchSpec> &CPP_specs,
729 const std::vector<SearchSpec> &C_specs, const SymbolContext &sc) {
730 for (const SearchSpec &C_spec : C_specs) {
731 const ConstString &name = C_spec.name;
Sean Callananb2814802016-02-12 21:11:25 +0000732
Kate Stoneb9c1b512016-09-06 20:57:50 +0000733 if (CPlusPlusLanguage::IsCPPMangledName(name.GetCString())) {
734 Mangled mangled(name, true);
735 ConstString demangled =
736 mangled.GetDemangledName(lldb::eLanguageTypeC_plus_plus);
Chaoren Lin74a1fc62016-02-24 03:15:21 +0000737
Kate Stoneb9c1b512016-09-06 20:57:50 +0000738 if (demangled) {
739 ConstString best_alternate_mangled_name = FindBestAlternateMangledName(
740 demangled, lldb::eLanguageTypeC_plus_plus, sc);
Chaoren Lin74a1fc62016-02-24 03:15:21 +0000741
Kate Stoneb9c1b512016-09-06 20:57:50 +0000742 if (best_alternate_mangled_name) {
743 CPP_specs.push_back(best_alternate_mangled_name);
Sean Callananb2814802016-02-12 21:11:25 +0000744 }
Chaoren Lin74a1fc62016-02-24 03:15:21 +0000745
Kate Stoneb9c1b512016-09-06 20:57:50 +0000746 CPP_specs.push_back(SearchSpec(demangled, lldb::eFunctionNameTypeFull));
747 }
Sean Callananb2814802016-02-12 21:11:25 +0000748 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000749
Luke Drummondf5bb1d62016-12-19 17:22:44 +0000750 std::set<ConstString> alternates;
751 CPlusPlusLanguage::FindAlternateFunctionManglings(name, alternates);
752 CPP_specs.insert(CPP_specs.end(), alternates.begin(), alternates.end());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000753 }
Sean Callananb2814802016-02-12 21:11:25 +0000754}
755
Kate Stoneb9c1b512016-09-06 20:57:50 +0000756void IRExecutionUnit::CollectFallbackNames(
757 std::vector<SearchSpec> &fallback_specs,
758 const std::vector<SearchSpec> &C_specs) {
759 // As a last-ditch fallback, try the base name for C++ names. It's terrible,
760 // but the DWARF doesn't always encode "extern C" correctly.
761
762 for (const SearchSpec &C_spec : C_specs) {
763 const ConstString &name = C_spec.name;
764
765 if (CPlusPlusLanguage::IsCPPMangledName(name.GetCString())) {
766 Mangled mangled_name(name);
767 ConstString demangled_name =
768 mangled_name.GetDemangledName(lldb::eLanguageTypeC_plus_plus);
769 if (!demangled_name.IsEmpty()) {
770 const char *demangled_cstr = demangled_name.AsCString();
771 const char *lparen_loc = strchr(demangled_cstr, '(');
772 if (lparen_loc) {
773 llvm::StringRef base_name(demangled_cstr,
774 lparen_loc - demangled_cstr);
775 fallback_specs.push_back(ConstString(base_name));
Sean Callanan34ab28a2016-06-02 17:59:47 +0000776 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000777 }
Sean Callanan34ab28a2016-06-02 17:59:47 +0000778 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000779 }
Sean Callanan34ab28a2016-06-02 17:59:47 +0000780}
781
Kate Stoneb9c1b512016-09-06 20:57:50 +0000782lldb::addr_t IRExecutionUnit::FindInSymbols(
783 const std::vector<IRExecutionUnit::SearchSpec> &specs,
784 const lldb_private::SymbolContext &sc) {
785 Target *target = sc.target_sp.get();
Sean Callanan34ab28a2016-06-02 17:59:47 +0000786
Kate Stoneb9c1b512016-09-06 20:57:50 +0000787 if (!target) {
788 // we shouldn't be doing any symbol lookup at all without a target
789 return LLDB_INVALID_ADDRESS;
790 }
Sean Callananfed0e7582016-02-23 23:09:06 +0000791
Kate Stoneb9c1b512016-09-06 20:57:50 +0000792 for (const SearchSpec &spec : specs) {
793 SymbolContextList sc_list;
Sean Callananfed0e7582016-02-23 23:09:06 +0000794
Kate Stoneb9c1b512016-09-06 20:57:50 +0000795 lldb::addr_t best_internal_load_address = LLDB_INVALID_ADDRESS;
Sean Callananfed0e7582016-02-23 23:09:06 +0000796
Kate Stoneb9c1b512016-09-06 20:57:50 +0000797 std::function<bool(lldb::addr_t &, SymbolContextList &,
798 const lldb_private::SymbolContext &)>
799 get_external_load_address = [&best_internal_load_address, target](
800 lldb::addr_t &load_address, SymbolContextList &sc_list,
801 const lldb_private::SymbolContext &sc) -> lldb::addr_t {
802 load_address = LLDB_INVALID_ADDRESS;
Sean Callananfed0e7582016-02-23 23:09:06 +0000803
Kate Stoneb9c1b512016-09-06 20:57:50 +0000804 for (size_t si = 0, se = sc_list.GetSize(); si < se; ++si) {
805 SymbolContext candidate_sc;
806
807 sc_list.GetContextAtIndex(si, candidate_sc);
808
809 const bool is_external =
810 (candidate_sc.function) ||
811 (candidate_sc.symbol && candidate_sc.symbol->IsExternal());
812 if (candidate_sc.symbol) {
813 load_address = candidate_sc.symbol->ResolveCallableAddress(*target);
814
815 if (load_address == LLDB_INVALID_ADDRESS) {
816 if (target->GetProcessSP())
817 load_address =
818 candidate_sc.symbol->GetAddress().GetLoadAddress(target);
819 else
820 load_address = candidate_sc.symbol->GetAddress().GetFileAddress();
821 }
822 }
823
824 if (load_address == LLDB_INVALID_ADDRESS && candidate_sc.function) {
825 if (target->GetProcessSP())
826 load_address = candidate_sc.function->GetAddressRange()
827 .GetBaseAddress()
828 .GetLoadAddress(target);
829 else
830 load_address = candidate_sc.function->GetAddressRange()
831 .GetBaseAddress()
832 .GetFileAddress();
833 }
834
835 if (load_address != LLDB_INVALID_ADDRESS) {
836 if (is_external) {
837 return true;
838 } else if (best_internal_load_address == LLDB_INVALID_ADDRESS) {
839 best_internal_load_address = load_address;
Sean Callananfed0e7582016-02-23 23:09:06 +0000840 load_address = LLDB_INVALID_ADDRESS;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000841 }
842 }
843 }
Sean Callananfed0e7582016-02-23 23:09:06 +0000844
Kate Stoneb9c1b512016-09-06 20:57:50 +0000845 return false;
846 };
Sean Callananfed0e7582016-02-23 23:09:06 +0000847
Kate Stoneb9c1b512016-09-06 20:57:50 +0000848 if (sc.module_sp) {
849 sc.module_sp->FindFunctions(spec.name, NULL, spec.mask,
850 true, // include_symbols
851 false, // include_inlines
852 true, // append
853 sc_list);
854 }
Sean Callananfed0e7582016-02-23 23:09:06 +0000855
Kate Stoneb9c1b512016-09-06 20:57:50 +0000856 lldb::addr_t load_address = LLDB_INVALID_ADDRESS;
Ted Woodwardeee554d2016-03-09 22:05:17 +0000857
Kate Stoneb9c1b512016-09-06 20:57:50 +0000858 if (get_external_load_address(load_address, sc_list, sc)) {
859 return load_address;
860 } else {
861 sc_list.Clear();
862 }
863
864 if (sc_list.GetSize() == 0 && sc.target_sp) {
865 sc.target_sp->GetImages().FindFunctions(spec.name, spec.mask,
866 true, // include_symbols
867 false, // include_inlines
868 true, // append
869 sc_list);
870 }
871
872 if (get_external_load_address(load_address, sc_list, sc)) {
873 return load_address;
874 } else {
875 sc_list.Clear();
876 }
877
878 if (sc_list.GetSize() == 0 && sc.target_sp) {
879 sc.target_sp->GetImages().FindSymbolsWithNameAndType(
880 spec.name, lldb::eSymbolTypeAny, sc_list);
881 }
882
883 if (get_external_load_address(load_address, sc_list, sc)) {
884 return load_address;
885 }
Adrian Prantl05097242018-04-30 16:49:04 +0000886 // if there are any searches we try after this, add an sc_list.Clear() in
887 // an "else" clause here
Kate Stoneb9c1b512016-09-06 20:57:50 +0000888
889 if (best_internal_load_address != LLDB_INVALID_ADDRESS) {
890 return best_internal_load_address;
891 }
892 }
893
894 return LLDB_INVALID_ADDRESS;
895}
896
897lldb::addr_t
898IRExecutionUnit::FindInRuntimes(const std::vector<SearchSpec> &specs,
899 const lldb_private::SymbolContext &sc) {
900 lldb::TargetSP target_sp = sc.target_sp;
901
902 if (!target_sp) {
903 return LLDB_INVALID_ADDRESS;
904 }
905
906 lldb::ProcessSP process_sp = sc.target_sp->GetProcessSP();
907
908 if (!process_sp) {
909 return LLDB_INVALID_ADDRESS;
910 }
911
912 ObjCLanguageRuntime *runtime = process_sp->GetObjCLanguageRuntime();
913
914 if (runtime) {
915 for (const SearchSpec &spec : specs) {
916 lldb::addr_t symbol_load_addr = runtime->LookupRuntimeSymbol(spec.name);
917
918 if (symbol_load_addr != LLDB_INVALID_ADDRESS)
919 return symbol_load_addr;
920 }
921 }
922
923 return LLDB_INVALID_ADDRESS;
924}
925
926lldb::addr_t IRExecutionUnit::FindInUserDefinedSymbols(
927 const std::vector<SearchSpec> &specs,
928 const lldb_private::SymbolContext &sc) {
929 lldb::TargetSP target_sp = sc.target_sp;
930
931 for (const SearchSpec &spec : specs) {
932 lldb::addr_t symbol_load_addr = target_sp->GetPersistentSymbol(spec.name);
933
934 if (symbol_load_addr != LLDB_INVALID_ADDRESS)
935 return symbol_load_addr;
936 }
937
938 return LLDB_INVALID_ADDRESS;
939}
940
941lldb::addr_t
942IRExecutionUnit::FindSymbol(const lldb_private::ConstString &name) {
943 std::vector<SearchSpec> candidate_C_names;
944 std::vector<SearchSpec> candidate_CPlusPlus_names;
945
946 CollectCandidateCNames(candidate_C_names, name);
947
948 lldb::addr_t ret = FindInSymbols(candidate_C_names, m_sym_ctx);
949 if (ret == LLDB_INVALID_ADDRESS)
950 ret = FindInRuntimes(candidate_C_names, m_sym_ctx);
951
952 if (ret == LLDB_INVALID_ADDRESS)
953 ret = FindInUserDefinedSymbols(candidate_C_names, m_sym_ctx);
954
955 if (ret == LLDB_INVALID_ADDRESS) {
956 CollectCandidateCPlusPlusNames(candidate_CPlusPlus_names, candidate_C_names,
957 m_sym_ctx);
958 ret = FindInSymbols(candidate_CPlusPlus_names, m_sym_ctx);
959 }
960
961 if (ret == LLDB_INVALID_ADDRESS) {
962 std::vector<SearchSpec> candidate_fallback_names;
963
964 CollectFallbackNames(candidate_fallback_names, candidate_C_names);
965 ret = FindInSymbols(candidate_fallback_names, m_sym_ctx);
966 }
967
968 return ret;
969}
970
971void IRExecutionUnit::GetStaticInitializers(
972 std::vector<lldb::addr_t> &static_initializers) {
973 if (llvm::GlobalVariable *global_ctors =
974 m_module->getNamedGlobal("llvm.global_ctors")) {
975 if (llvm::ConstantArray *ctor_array = llvm::dyn_cast<llvm::ConstantArray>(
976 global_ctors->getInitializer())) {
977 for (llvm::Use &ctor_use : ctor_array->operands()) {
978 if (llvm::ConstantStruct *ctor_struct =
979 llvm::dyn_cast<llvm::ConstantStruct>(ctor_use)) {
980 lldbassert(ctor_struct->getNumOperands() ==
981 3); // this is standardized
982 if (llvm::Function *ctor_function =
983 llvm::dyn_cast<llvm::Function>(ctor_struct->getOperand(1))) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000984 ConstString ctor_function_name_cs(ctor_function->getName().str());
985
986 for (JittedFunction &jitted_function : m_jitted_functions) {
987 if (ctor_function_name_cs == jitted_function.m_name) {
988 if (jitted_function.m_remote_addr != LLDB_INVALID_ADDRESS) {
989 static_initializers.push_back(jitted_function.m_remote_addr);
Ted Woodwardeee554d2016-03-09 22:05:17 +0000990 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000991 break;
992 }
Sean Callananfed0e7582016-02-23 23:09:06 +0000993 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000994 }
Sean Callananb2814802016-02-12 21:11:25 +0000995 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000996 }
Sean Callananb2814802016-02-12 21:11:25 +0000997 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000998 }
Sean Callananbd4dc692016-03-21 22:23:38 +0000999}
1000
Jim Ingham27e5fe82015-01-27 18:03:05 +00001001uint64_t
Kate Stoneb9c1b512016-09-06 20:57:50 +00001002IRExecutionUnit::MemoryManager::getSymbolAddress(const std::string &Name) {
1003 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
Greg Claytond6171a72015-07-02 16:43:49 +00001004
Kate Stoneb9c1b512016-09-06 20:57:50 +00001005 ConstString name_cs(Name.c_str());
Chaoren Lin74a1fc62016-02-24 03:15:21 +00001006
Kate Stoneb9c1b512016-09-06 20:57:50 +00001007 lldb::addr_t ret = m_parent.FindSymbol(name_cs);
Chaoren Lin74a1fc62016-02-24 03:15:21 +00001008
Kate Stoneb9c1b512016-09-06 20:57:50 +00001009 if (ret == LLDB_INVALID_ADDRESS) {
1010 if (log)
1011 log->Printf(
1012 "IRExecutionUnit::getSymbolAddress(Name=\"%s\") = <not found>",
1013 Name.c_str());
Sean Callananb2814802016-02-12 21:11:25 +00001014
Kate Stoneb9c1b512016-09-06 20:57:50 +00001015 m_parent.ReportSymbolLookupError(name_cs);
1016 return 0xbad0bad0;
1017 } else {
1018 if (log)
1019 log->Printf("IRExecutionUnit::getSymbolAddress(Name=\"%s\") = %" PRIx64,
1020 Name.c_str(), ret);
1021 return ret;
1022 }
Jim Ingham27e5fe82015-01-27 18:03:05 +00001023}
1024
Kate Stoneb9c1b512016-09-06 20:57:50 +00001025void *IRExecutionUnit::MemoryManager::getPointerToNamedFunction(
1026 const std::string &Name, bool AbortOnFailure) {
1027 assert(sizeof(void *) == 8);
Chaoren Lin74a1fc62016-02-24 03:15:21 +00001028
Kate Stoneb9c1b512016-09-06 20:57:50 +00001029 return (void *)getSymbolAddress(Name);
Jim Ingham27e5fe82015-01-27 18:03:05 +00001030}
1031
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001032lldb::addr_t
Kate Stoneb9c1b512016-09-06 20:57:50 +00001033IRExecutionUnit::GetRemoteAddressForLocal(lldb::addr_t local_address) {
1034 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
Sean Callananffae9442013-06-27 01:42:47 +00001035
Kate Stoneb9c1b512016-09-06 20:57:50 +00001036 for (AllocationRecord &record : m_records) {
1037 if (local_address >= record.m_host_address &&
1038 local_address < record.m_host_address + record.m_size) {
1039 if (record.m_process_address == LLDB_INVALID_ADDRESS)
1040 return LLDB_INVALID_ADDRESS;
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +00001041
Kate Stoneb9c1b512016-09-06 20:57:50 +00001042 lldb::addr_t ret =
1043 record.m_process_address + (local_address - record.m_host_address);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +00001044
Kate Stoneb9c1b512016-09-06 20:57:50 +00001045 if (log) {
1046 log->Printf(
1047 "IRExecutionUnit::GetRemoteAddressForLocal() found 0x%" PRIx64
1048 " in [0x%" PRIx64 "..0x%" PRIx64 "], and returned 0x%" PRIx64
1049 " from [0x%" PRIx64 "..0x%" PRIx64 "].",
1050 local_address, (uint64_t)record.m_host_address,
1051 (uint64_t)record.m_host_address + (uint64_t)record.m_size, ret,
1052 record.m_process_address, record.m_process_address + record.m_size);
1053 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +00001054
Kate Stoneb9c1b512016-09-06 20:57:50 +00001055 return ret;
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001056 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001057 }
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001058
Kate Stoneb9c1b512016-09-06 20:57:50 +00001059 return LLDB_INVALID_ADDRESS;
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001060}
1061
1062IRExecutionUnit::AddrRange
Kate Stoneb9c1b512016-09-06 20:57:50 +00001063IRExecutionUnit::GetRemoteRangeForLocal(lldb::addr_t local_address) {
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 AddrRange(0, 0);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +00001069
Kate Stoneb9c1b512016-09-06 20:57:50 +00001070 return AddrRange(record.m_process_address, record.m_size);
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001071 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001072 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +00001073
Kate Stoneb9c1b512016-09-06 20:57:50 +00001074 return AddrRange(0, 0);
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001075}
1076
Kate Stoneb9c1b512016-09-06 20:57:50 +00001077bool IRExecutionUnit::CommitOneAllocation(lldb::ProcessSP &process_sp,
Zachary Turner97206d52017-05-12 04:51:55 +00001078 Status &error,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001079 AllocationRecord &record) {
1080 if (record.m_process_address != LLDB_INVALID_ADDRESS) {
1081 return true;
1082 }
1083
1084 switch (record.m_sect_type) {
1085 case lldb::eSectionTypeInvalid:
1086 case lldb::eSectionTypeDWARFDebugAbbrev:
1087 case lldb::eSectionTypeDWARFDebugAddr:
1088 case lldb::eSectionTypeDWARFDebugAranges:
Tamas Berghammer963ce482017-08-25 13:56:14 +00001089 case lldb::eSectionTypeDWARFDebugCuIndex:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001090 case lldb::eSectionTypeDWARFDebugFrame:
1091 case lldb::eSectionTypeDWARFDebugInfo:
1092 case lldb::eSectionTypeDWARFDebugLine:
1093 case lldb::eSectionTypeDWARFDebugLoc:
George Rimare4dee262018-10-23 09:46:15 +00001094 case lldb::eSectionTypeDWARFDebugLocLists:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001095 case lldb::eSectionTypeDWARFDebugMacInfo:
1096 case lldb::eSectionTypeDWARFDebugPubNames:
1097 case lldb::eSectionTypeDWARFDebugPubTypes:
1098 case lldb::eSectionTypeDWARFDebugRanges:
1099 case lldb::eSectionTypeDWARFDebugStr:
1100 case lldb::eSectionTypeDWARFDebugStrOffsets:
1101 case lldb::eSectionTypeDWARFAppleNames:
1102 case lldb::eSectionTypeDWARFAppleTypes:
1103 case lldb::eSectionTypeDWARFAppleNamespaces:
1104 case lldb::eSectionTypeDWARFAppleObjC:
Jan Kratochvile4777a92018-04-29 19:47:48 +00001105 case lldb::eSectionTypeDWARFGNUDebugAltLink:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001106 error.Clear();
1107 break;
1108 default:
1109 const bool zero_memory = false;
1110 record.m_process_address =
1111 Malloc(record.m_size, record.m_alignment, record.m_permissions,
1112 eAllocationPolicyProcessOnly, zero_memory, error);
1113 break;
1114 }
1115
1116 return error.Success();
1117}
1118
1119bool IRExecutionUnit::CommitAllocations(lldb::ProcessSP &process_sp) {
1120 bool ret = true;
1121
Zachary Turner97206d52017-05-12 04:51:55 +00001122 lldb_private::Status err;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001123
1124 for (AllocationRecord &record : m_records) {
1125 ret = CommitOneAllocation(process_sp, err, record);
1126
1127 if (!ret) {
1128 break;
Sean Callananbd4dc692016-03-21 22:23:38 +00001129 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001130 }
1131
1132 if (!ret) {
1133 for (AllocationRecord &record : m_records) {
1134 if (record.m_process_address != LLDB_INVALID_ADDRESS) {
1135 Free(record.m_process_address, err);
1136 record.m_process_address = LLDB_INVALID_ADDRESS;
1137 }
Sean Callananbd4dc692016-03-21 22:23:38 +00001138 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001139 }
1140
1141 return ret;
Sean Callananbd4dc692016-03-21 22:23:38 +00001142}
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +00001143
Kate Stoneb9c1b512016-09-06 20:57:50 +00001144void IRExecutionUnit::ReportAllocations(llvm::ExecutionEngine &engine) {
1145 m_reported_allocations = true;
Sean Callananbd4dc692016-03-21 22:23:38 +00001146
Kate Stoneb9c1b512016-09-06 20:57:50 +00001147 for (AllocationRecord &record : m_records) {
1148 if (record.m_process_address == LLDB_INVALID_ADDRESS)
1149 continue;
Sean Callananbd4dc692016-03-21 22:23:38 +00001150
Kate Stoneb9c1b512016-09-06 20:57:50 +00001151 if (record.m_section_id == eSectionIDInvalid)
1152 continue;
1153
1154 engine.mapSectionAddress((void *)record.m_host_address,
1155 record.m_process_address);
1156 }
1157
1158 // Trigger re-application of relocations.
1159 engine.finalizeObject();
1160}
1161
1162bool IRExecutionUnit::WriteData(lldb::ProcessSP &process_sp) {
1163 bool wrote_something = false;
1164 for (AllocationRecord &record : m_records) {
1165 if (record.m_process_address != LLDB_INVALID_ADDRESS) {
Zachary Turner97206d52017-05-12 04:51:55 +00001166 lldb_private::Status err;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001167 WriteMemory(record.m_process_address, (uint8_t *)record.m_host_address,
1168 record.m_size, err);
1169 if (err.Success())
1170 wrote_something = true;
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001171 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001172 }
1173 return wrote_something;
1174}
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +00001175
Kate Stoneb9c1b512016-09-06 20:57:50 +00001176void IRExecutionUnit::AllocationRecord::dump(Log *log) {
1177 if (!log)
1178 return;
1179
1180 log->Printf("[0x%llx+0x%llx]->0x%llx (alignment %d, section ID %d, name %s)",
1181 (unsigned long long)m_host_address, (unsigned long long)m_size,
1182 (unsigned long long)m_process_address, (unsigned)m_alignment,
1183 (unsigned)m_section_id, m_name.c_str());
1184}
1185
1186lldb::ByteOrder IRExecutionUnit::GetByteOrder() const {
1187 ExecutionContext exe_ctx(GetBestExecutionContextScope());
1188 return exe_ctx.GetByteOrder();
1189}
1190
1191uint32_t IRExecutionUnit::GetAddressByteSize() const {
1192 ExecutionContext exe_ctx(GetBestExecutionContextScope());
1193 return exe_ctx.GetAddressByteSize();
1194}
1195
1196void IRExecutionUnit::PopulateSymtab(lldb_private::ObjectFile *obj_file,
1197 lldb_private::Symtab &symtab) {
1198 // No symbols yet...
1199}
1200
1201void IRExecutionUnit::PopulateSectionList(
1202 lldb_private::ObjectFile *obj_file,
1203 lldb_private::SectionList &section_list) {
1204 for (AllocationRecord &record : m_records) {
1205 if (record.m_size > 0) {
1206 lldb::SectionSP section_sp(new lldb_private::Section(
1207 obj_file->GetModule(), obj_file, record.m_section_id,
1208 ConstString(record.m_name), record.m_sect_type,
1209 record.m_process_address, record.m_size,
1210 record.m_host_address, // file_offset (which is the host address for
1211 // the data)
1212 record.m_size, // file_size
1213 0,
1214 record.m_permissions)); // flags
1215 section_list.AddSection(section_sp);
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001216 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001217 }
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001218}
1219
Kate Stoneb9c1b512016-09-06 20:57:50 +00001220bool IRExecutionUnit::GetArchitecture(lldb_private::ArchSpec &arch) {
1221 ExecutionContext exe_ctx(GetBestExecutionContextScope());
1222 Target *target = exe_ctx.GetTargetPtr();
1223 if (target)
1224 arch = target->GetArchitecture();
1225 else
1226 arch.Clear();
1227 return arch.IsValid();
1228}
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +00001229
Kate Stoneb9c1b512016-09-06 20:57:50 +00001230lldb::ModuleSP IRExecutionUnit::GetJITModule() {
1231 ExecutionContext exe_ctx(GetBestExecutionContextScope());
1232 Target *target = exe_ctx.GetTargetPtr();
Zachary Turner8e8d4b92018-05-23 23:56:09 +00001233 if (!target)
1234 return nullptr;
1235
1236 auto Delegate = std::static_pointer_cast<lldb_private::ObjectFileJITDelegate>(
1237 shared_from_this());
1238
1239 lldb::ModuleSP jit_module_sp =
1240 lldb_private::Module::CreateModuleFromObjectFile<ObjectFileJIT>(Delegate);
1241 if (!jit_module_sp)
1242 return nullptr;
1243
1244 bool changed = false;
1245 jit_module_sp->SetLoadAddress(*target, 0, true, changed);
1246 return jit_module_sp;
Greg Clayton23f8c952014-03-24 23:10:19 +00001247}