blob: be53f37e0bcc7f35acaa10379ef8349a373c4b4e [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"
36
Sean Callanan8dfb68e2013-03-19 00:10:07 +000037using namespace lldb_private;
38
Kate Stoneb9c1b512016-09-06 20:57:50 +000039IRExecutionUnit::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) {}
Sean Callanan8dfb68e2013-03-19 00:10:07 +000051
Kate Stoneb9c1b512016-09-06 20:57:50 +000052lldb::addr_t IRExecutionUnit::WriteNow(const uint8_t *bytes, size_t size,
Zachary Turner97206d52017-05-12 04:51:55 +000053 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +000054 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);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +000058
Kate Stoneb9c1b512016-09-06 20:57:50 +000059 if (!error.Success())
60 return LLDB_INVALID_ADDRESS;
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +000061
Kate Stoneb9c1b512016-09-06 20:57:50 +000062 WriteMemory(allocation_process_addr, bytes, size, error);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +000063
Kate Stoneb9c1b512016-09-06 20:57:50 +000064 if (!error.Success()) {
Zachary Turner97206d52017-05-12 04:51:55 +000065 Status err;
Kate Stoneb9c1b512016-09-06 20:57:50 +000066 Free(allocation_process_addr, err);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +000067
Kate Stoneb9c1b512016-09-06 20:57:50 +000068 return LLDB_INVALID_ADDRESS;
69 }
Sean Callanan8dfb68e2013-03-19 00:10:07 +000070
Kate Stoneb9c1b512016-09-06 20:57:50 +000071 if (Log *log =
72 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)) {
73 DataBufferHeap my_buffer(size, 0);
Zachary Turner97206d52017-05-12 04:51:55 +000074 Status err;
Kate Stoneb9c1b512016-09-06 20:57:50 +000075 ReadMemory(my_buffer.GetBytes(), allocation_process_addr, size, err);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +000076
Kate Stoneb9c1b512016-09-06 20:57:50 +000077 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,
Sean Callanan8dfb68e2013-03-19 00:10:07 +000082 DataExtractor::TypeUInt8);
83 }
Kate Stoneb9c1b512016-09-06 20:57:50 +000084 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +000085
Kate Stoneb9c1b512016-09-06 20:57:50 +000086 return allocation_process_addr;
87}
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +000088
Kate Stoneb9c1b512016-09-06 20:57:50 +000089void IRExecutionUnit::FreeNow(lldb::addr_t allocation) {
90 if (allocation == LLDB_INVALID_ADDRESS)
91 return;
92
Zachary Turner97206d52017-05-12 04:51:55 +000093 Status err;
Kate Stoneb9c1b512016-09-06 20:57:50 +000094
95 Free(allocation, err);
96}
97
Zachary Turner97206d52017-05-12 04:51:55 +000098Status IRExecutionUnit::DisassembleFunction(Stream &stream,
99 lldb::ProcessSP &process_wp) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000100 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
101
102 ExecutionContext exe_ctx(process_wp);
103
Zachary Turner97206d52017-05-12 04:51:55 +0000104 Status ret;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000105
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());
Sean Callanan8dfb68e2013-03-19 00:10:07 +0000122 return ret;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000123 }
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();
Zachary Turner97206d52017-05-12 04:51:55 +0000155 Status err;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000156 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;
Sean Callanan8dfb68e2013-03-19 00:10:07 +0000202}
203
Kate Stoneb9c1b512016-09-06 20:57:50 +0000204static void ReportInlineAsmError(const llvm::SMDiagnostic &diagnostic,
205 void *Context, unsigned LocCookie) {
Zachary Turner97206d52017-05-12 04:51:55 +0000206 Status *err = static_cast<Status *>(Context);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000207
Kate Stoneb9c1b512016-09-06 20:57:50 +0000208 if (err && err->Success()) {
209 err->SetErrorToGenericError();
210 err->SetErrorStringWithFormat("Inline assembly error: %s",
211 diagnostic.getMessage().str().c_str());
212 }
Sean Callanan44bc6572013-03-27 03:09:55 +0000213}
214
Kate Stoneb9c1b512016-09-06 20:57:50 +0000215void IRExecutionUnit::ReportSymbolLookupError(const ConstString &name) {
216 m_failed_lookups.push_back(name);
Jim Ingham27e5fe82015-01-27 18:03:05 +0000217}
218
Zachary Turner97206d52017-05-12 04:51:55 +0000219void IRExecutionUnit::GetRunnableInfo(Status &error, lldb::addr_t &func_addr,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000220 lldb::addr_t &func_end) {
221 lldb::ProcessSP process_sp(GetProcessWP().lock());
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000222
Kate Stoneb9c1b512016-09-06 20:57:50 +0000223 static std::recursive_mutex s_runnable_info_mutex;
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000224
Kate Stoneb9c1b512016-09-06 20:57:50 +0000225 func_addr = LLDB_INVALID_ADDRESS;
226 func_end = LLDB_INVALID_ADDRESS;
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000227
Kate Stoneb9c1b512016-09-06 20:57:50 +0000228 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 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000234
Kate Stoneb9c1b512016-09-06 20:57:50 +0000235 if (m_did_jit) {
Sean Callanan5a1af4e2013-04-05 02:22:57 +0000236 func_addr = m_function_load_addr;
237 func_end = m_function_end_load_addr;
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000238
Sean Callanan5a1af4e2013-04-05 02:22:57 +0000239 return;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000240 };
Sean Callanan8dfb68e2013-03-19 00:10:07 +0000241
Kate Stoneb9c1b512016-09-06 20:57:50 +0000242 std::lock_guard<std::recursive_mutex> guard(s_runnable_info_mutex);
Sean Callanan8dfb68e2013-03-19 00:10:07 +0000243
Kate Stoneb9c1b512016-09-06 20:57:50 +0000244 m_did_jit = true;
Sean Callanan8dfb68e2013-03-19 00:10:07 +0000245
Kate Stoneb9c1b512016-09-06 20:57:50 +0000246 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan8dfb68e2013-03-19 00:10:07 +0000247
Kate Stoneb9c1b512016-09-06 20:57:50 +0000248 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;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000263
264 if (triple.isOSBinFormatELF()) {
265 relocModel = llvm::Reloc::Static;
266 } else {
267 relocModel = llvm::Reloc::PIC_;
268 }
269
Kate Stoneb9c1b512016-09-06 20:57:50 +0000270 m_module_ap->getContext().setInlineAsmDiagnosticHandler(ReportInlineAsmError,
271 &error);
272
273 llvm::EngineBuilder builder(std::move(m_module_ap));
274
275 builder.setEngineKind(llvm::EngineKind::JIT)
276 .setErrorStr(&error_string)
277 .setRelocationModel(relocModel)
278 .setMCJITMemoryManager(
279 std::unique_ptr<MemoryManager>(new MemoryManager(*this)))
Pavel Labathd7396362017-11-13 14:03:17 +0000280 .setOptLevel(llvm::CodeGenOpt::Less);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000281
282 llvm::StringRef mArch;
283 llvm::StringRef mCPU;
284 llvm::SmallVector<std::string, 0> mAttrs;
285
286 for (std::string &feature : m_cpu_features)
287 mAttrs.push_back(feature);
288
289 llvm::TargetMachine *target_machine =
290 builder.selectTarget(triple, mArch, mCPU, mAttrs);
291
292 m_execution_engine_ap.reset(builder.create(target_machine));
293
294 m_strip_underscore =
295 (m_execution_engine_ap->getDataLayout().getGlobalPrefix() == '_');
296
297 if (!m_execution_engine_ap.get()) {
298 error.SetErrorToGenericError();
299 error.SetErrorStringWithFormat("Couldn't JIT the function: %s",
300 error_string.c_str());
301 return;
302 }
303
Sean Callanan5deb06e2016-09-26 20:18:51 +0000304 class ObjectDumper : public llvm::ObjectCache {
305 public:
306 void notifyObjectCompiled(const llvm::Module *module,
307 llvm::MemoryBufferRef object) override {
308 int fd = 0;
309 llvm::SmallVector<char, 256> result_path;
310 std::string object_name_model =
311 "jit-object-" + module->getModuleIdentifier() + "-%%%.o";
312 (void)llvm::sys::fs::createUniqueFile(object_name_model, fd, result_path);
313 llvm::raw_fd_ostream fds(fd, true);
314 fds.write(object.getBufferStart(), object.getBufferSize());
315 }
316
317 std::unique_ptr<llvm::MemoryBuffer>
318 getObject(const llvm::Module *module) override {
319 // Return nothing - we're just abusing the object-cache mechanism to dump
320 // objects.
321 return nullptr;
322 }
323 };
324
325 if (process_sp->GetTarget().GetEnableSaveObjects()) {
326 m_object_cache_ap = llvm::make_unique<ObjectDumper>();
327 m_execution_engine_ap->setObjectCache(m_object_cache_ap.get());
328 }
329
Kate Stoneb9c1b512016-09-06 20:57:50 +0000330 // Make sure we see all sections, including ones that don't have
331 // relocations...
332 m_execution_engine_ap->setProcessAllSections(true);
333
334 m_execution_engine_ap->DisableLazyCompilation();
335
336 for (llvm::Function &function : *m_module) {
337 if (function.isDeclaration() || function.hasPrivateLinkage())
338 continue;
339
340 const bool external =
341 function.hasExternalLinkage() || function.hasLinkOnceODRLinkage();
342
343 void *fun_ptr = m_execution_engine_ap->getPointerToFunction(&function);
344
345 if (!error.Success()) {
346 // We got an error through our callback!
347 return;
Greg Clayton23f8c952014-03-24 23:10:19 +0000348 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000349
Kate Stoneb9c1b512016-09-06 20:57:50 +0000350 if (!fun_ptr) {
351 error.SetErrorToGenericError();
352 error.SetErrorStringWithFormat(
353 "'%s' was in the JITted module but wasn't lowered",
354 function.getName().str().c_str());
355 return;
356 }
357 m_jitted_functions.push_back(JittedFunction(
358 function.getName().str().c_str(), external, (lldb::addr_t)fun_ptr));
359 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000360
Kate Stoneb9c1b512016-09-06 20:57:50 +0000361 CommitAllocations(process_sp);
362 ReportAllocations(*m_execution_engine_ap);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000363
Kate Stoneb9c1b512016-09-06 20:57:50 +0000364 // We have to do this after calling ReportAllocations because for the MCJIT,
365 // getGlobalValueAddress
366 // will cause the JIT to perform all relocations. That can only be done once,
367 // and has to happen
368 // after we do the remapping from local -> remote.
369 // That means we don't know the local address of the Variables, but we don't
370 // need that for anything,
371 // so that's okay.
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000372
Kate Stoneb9c1b512016-09-06 20:57:50 +0000373 std::function<void(llvm::GlobalValue &)> RegisterOneValue = [this](
374 llvm::GlobalValue &val) {
375 if (val.hasExternalLinkage() && !val.isDeclaration()) {
376 uint64_t var_ptr_addr =
377 m_execution_engine_ap->getGlobalValueAddress(val.getName().str());
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000378
Kate Stoneb9c1b512016-09-06 20:57:50 +0000379 lldb::addr_t remote_addr = GetRemoteAddressForLocal(var_ptr_addr);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000380
Kate Stoneb9c1b512016-09-06 20:57:50 +0000381 // This is a really unfortunae API that sometimes returns local addresses
382 // and sometimes returns remote addresses, based on whether
383 // the variable was relocated during ReportAllocations or not.
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000384
Kate Stoneb9c1b512016-09-06 20:57:50 +0000385 if (remote_addr == LLDB_INVALID_ADDRESS) {
386 remote_addr = var_ptr_addr;
387 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000388
Kate Stoneb9c1b512016-09-06 20:57:50 +0000389 if (var_ptr_addr != 0)
390 m_jitted_global_variables.push_back(JittedGlobalVariable(
391 val.getName().str().c_str(), LLDB_INVALID_ADDRESS, remote_addr));
392 }
393 };
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000394
Kate Stoneb9c1b512016-09-06 20:57:50 +0000395 for (llvm::GlobalVariable &global_var : m_module->getGlobalList()) {
396 RegisterOneValue(global_var);
397 }
398
399 for (llvm::GlobalAlias &global_alias : m_module->getAliasList()) {
400 RegisterOneValue(global_alias);
401 }
402
403 WriteData(process_sp);
404
405 if (m_failed_lookups.size()) {
406 StreamString ss;
407
408 ss.PutCString("Couldn't lookup symbols:\n");
409
410 bool emitNewLine = false;
411
412 for (const ConstString &failed_lookup : m_failed_lookups) {
413 if (emitNewLine)
414 ss.PutCString("\n");
415 emitNewLine = true;
416 ss.PutCString(" ");
417 ss.PutCString(Mangled(failed_lookup)
418 .GetDemangledName(lldb::eLanguageTypeObjC_plus_plus)
419 .AsCString());
420 }
421
422 m_failed_lookups.clear();
423
Zachary Turnerc1564272016-11-16 21:15:24 +0000424 error.SetErrorString(ss.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000425
426 return;
427 }
428
429 m_function_load_addr = LLDB_INVALID_ADDRESS;
430 m_function_end_load_addr = LLDB_INVALID_ADDRESS;
431
432 for (JittedFunction &jitted_function : m_jitted_functions) {
433 jitted_function.m_remote_addr =
434 GetRemoteAddressForLocal(jitted_function.m_local_addr);
435
436 if (!m_name.IsEmpty() && jitted_function.m_name == m_name) {
437 AddrRange func_range =
438 GetRemoteRangeForLocal(jitted_function.m_local_addr);
439 m_function_end_load_addr = func_range.first + func_range.second;
440 m_function_load_addr = jitted_function.m_remote_addr;
441 }
442 }
443
444 if (log) {
445 log->Printf("Code can be run in the target.");
446
447 StreamString disassembly_stream;
448
Zachary Turner97206d52017-05-12 04:51:55 +0000449 Status err = DisassembleFunction(disassembly_stream, process_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000450
451 if (!err.Success()) {
452 log->Printf("Couldn't disassemble function : %s",
453 err.AsCString("unknown error"));
454 } else {
455 log->Printf("Function disassembly:\n%s", disassembly_stream.GetData());
456 }
457
458 log->Printf("Sections: ");
459 for (AllocationRecord &record : m_records) {
460 if (record.m_process_address != LLDB_INVALID_ADDRESS) {
461 record.dump(log);
462
463 DataBufferHeap my_buffer(record.m_size, 0);
Zachary Turner97206d52017-05-12 04:51:55 +0000464 Status err;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000465 ReadMemory(my_buffer.GetBytes(), record.m_process_address,
466 record.m_size, err);
467
468 if (err.Success()) {
469 DataExtractor my_extractor(my_buffer.GetBytes(),
470 my_buffer.GetByteSize(),
471 lldb::eByteOrderBig, 8);
472 my_extractor.PutToLog(log, 0, my_buffer.GetByteSize(),
473 record.m_process_address, 16,
474 DataExtractor::TypeUInt8);
Greg Clayton23f8c952014-03-24 23:10:19 +0000475 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000476 } else {
477 record.dump(log);
478
479 DataExtractor my_extractor((const void *)record.m_host_address,
480 record.m_size, lldb::eByteOrderBig, 8);
481 my_extractor.PutToLog(log, 0, record.m_size, record.m_host_address, 16,
482 DataExtractor::TypeUInt8);
483 }
484 }
485 }
486
487 func_addr = m_function_load_addr;
488 func_end = m_function_end_load_addr;
489
490 return;
491}
492
493IRExecutionUnit::~IRExecutionUnit() {
494 m_module_ap.reset();
495 m_execution_engine_ap.reset();
496 m_context_ap.reset();
497}
498
499IRExecutionUnit::MemoryManager::MemoryManager(IRExecutionUnit &parent)
500 : m_default_mm_ap(new llvm::SectionMemoryManager()), m_parent(parent) {}
501
502IRExecutionUnit::MemoryManager::~MemoryManager() {}
503
504lldb::SectionType IRExecutionUnit::GetSectionTypeFromSectionName(
505 const llvm::StringRef &name, IRExecutionUnit::AllocationKind alloc_kind) {
506 lldb::SectionType sect_type = lldb::eSectionTypeCode;
507 switch (alloc_kind) {
508 case AllocationKind::Stub:
509 sect_type = lldb::eSectionTypeCode;
510 break;
511 case AllocationKind::Code:
512 sect_type = lldb::eSectionTypeCode;
513 break;
514 case AllocationKind::Data:
515 sect_type = lldb::eSectionTypeData;
516 break;
517 case AllocationKind::Global:
518 sect_type = lldb::eSectionTypeData;
519 break;
520 case AllocationKind::Bytes:
521 sect_type = lldb::eSectionTypeOther;
522 break;
523 }
524
525 if (!name.empty()) {
526 if (name.equals("__text") || name.equals(".text"))
527 sect_type = lldb::eSectionTypeCode;
528 else if (name.equals("__data") || name.equals(".data"))
529 sect_type = lldb::eSectionTypeCode;
530 else if (name.startswith("__debug_") || name.startswith(".debug_")) {
531 const uint32_t name_idx = name[0] == '_' ? 8 : 7;
532 llvm::StringRef dwarf_name(name.substr(name_idx));
533 switch (dwarf_name[0]) {
534 case 'a':
535 if (dwarf_name.equals("abbrev"))
536 sect_type = lldb::eSectionTypeDWARFDebugAbbrev;
537 else if (dwarf_name.equals("aranges"))
538 sect_type = lldb::eSectionTypeDWARFDebugAranges;
539 else if (dwarf_name.equals("addr"))
540 sect_type = lldb::eSectionTypeDWARFDebugAddr;
541 break;
542
543 case 'f':
544 if (dwarf_name.equals("frame"))
545 sect_type = lldb::eSectionTypeDWARFDebugFrame;
546 break;
547
548 case 'i':
549 if (dwarf_name.equals("info"))
550 sect_type = lldb::eSectionTypeDWARFDebugInfo;
551 break;
552
553 case 'l':
554 if (dwarf_name.equals("line"))
555 sect_type = lldb::eSectionTypeDWARFDebugLine;
556 else if (dwarf_name.equals("loc"))
557 sect_type = lldb::eSectionTypeDWARFDebugLoc;
558 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 }
587 } else if (name.startswith("__apple_") || name.startswith(".apple_")) {
Greg Clayton23f8c952014-03-24 23:10:19 +0000588#if 0
589 const uint32_t name_idx = name[0] == '_' ? 8 : 7;
590 llvm::StringRef apple_name(name.substr(name_idx));
591 switch (apple_name[0])
592 {
593 case 'n':
594 if (apple_name.equals("names"))
595 sect_type = lldb::eSectionTypeDWARFAppleNames;
596 else if (apple_name.equals("namespac") || apple_name.equals("namespaces"))
597 sect_type = lldb::eSectionTypeDWARFAppleNamespaces;
598 break;
599 case 't':
600 if (apple_name.equals("types"))
601 sect_type = lldb::eSectionTypeDWARFAppleTypes;
602 break;
603 case 'o':
604 if (apple_name.equals("objc"))
605 sect_type = lldb::eSectionTypeDWARFAppleObjC;
606 break;
607 default:
608 break;
609 }
610#else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000611 sect_type = lldb::eSectionTypeInvalid;
Greg Clayton23f8c952014-03-24 23:10:19 +0000612#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +0000613 } else if (name.equals("__objc_imageinfo"))
614 sect_type = lldb::eSectionTypeOther;
615 }
616 return sect_type;
Greg Clayton23f8c952014-03-24 23:10:19 +0000617}
618
Kate Stoneb9c1b512016-09-06 20:57:50 +0000619uint8_t *IRExecutionUnit::MemoryManager::allocateCodeSection(
620 uintptr_t Size, unsigned Alignment, unsigned SectionID,
621 llvm::StringRef SectionName) {
622 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000623
Kate Stoneb9c1b512016-09-06 20:57:50 +0000624 uint8_t *return_value = m_default_mm_ap->allocateCodeSection(
625 Size, Alignment, SectionID, SectionName);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000626
Kate Stoneb9c1b512016-09-06 20:57:50 +0000627 m_parent.m_records.push_back(AllocationRecord(
628 (uintptr_t)return_value,
629 lldb::ePermissionsReadable | lldb::ePermissionsExecutable,
630 GetSectionTypeFromSectionName(SectionName, AllocationKind::Code), Size,
631 Alignment, SectionID, SectionName.str().c_str()));
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000632
Kate Stoneb9c1b512016-09-06 20:57:50 +0000633 if (log) {
634 log->Printf("IRExecutionUnit::allocateCodeSection(Size=0x%" PRIx64
635 ", Alignment=%u, SectionID=%u) = %p",
636 (uint64_t)Size, Alignment, SectionID, (void *)return_value);
637 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000638
Kate Stoneb9c1b512016-09-06 20:57:50 +0000639 if (m_parent.m_reported_allocations) {
Zachary Turner97206d52017-05-12 04:51:55 +0000640 Status err;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000641 lldb::ProcessSP process_sp =
642 m_parent.GetBestExecutionContextScope()->CalculateProcess();
643
644 m_parent.CommitOneAllocation(process_sp, err, m_parent.m_records.back());
645 }
646
647 return return_value;
Sean Callanan8dfb68e2013-03-19 00:10:07 +0000648}
649
Kate Stoneb9c1b512016-09-06 20:57:50 +0000650uint8_t *IRExecutionUnit::MemoryManager::allocateDataSection(
651 uintptr_t Size, unsigned Alignment, unsigned SectionID,
652 llvm::StringRef SectionName, bool IsReadOnly) {
653 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan8dfb68e2013-03-19 00:10:07 +0000654
Kate Stoneb9c1b512016-09-06 20:57:50 +0000655 uint8_t *return_value = m_default_mm_ap->allocateDataSection(
656 Size, Alignment, SectionID, SectionName, IsReadOnly);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000657
Kate Stoneb9c1b512016-09-06 20:57:50 +0000658 uint32_t permissions = lldb::ePermissionsReadable;
659 if (!IsReadOnly)
660 permissions |= lldb::ePermissionsWritable;
661 m_parent.m_records.push_back(AllocationRecord(
662 (uintptr_t)return_value, permissions,
663 GetSectionTypeFromSectionName(SectionName, AllocationKind::Data), Size,
664 Alignment, SectionID, SectionName.str().c_str()));
665 if (log) {
666 log->Printf("IRExecutionUnit::allocateDataSection(Size=0x%" PRIx64
667 ", Alignment=%u, SectionID=%u) = %p",
668 (uint64_t)Size, Alignment, SectionID, (void *)return_value);
669 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000670
Kate Stoneb9c1b512016-09-06 20:57:50 +0000671 if (m_parent.m_reported_allocations) {
Zachary Turner97206d52017-05-12 04:51:55 +0000672 Status err;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000673 lldb::ProcessSP process_sp =
674 m_parent.GetBestExecutionContextScope()->CalculateProcess();
675
676 m_parent.CommitOneAllocation(process_sp, err, m_parent.m_records.back());
677 }
678
679 return return_value;
Sean Callanan8dfb68e2013-03-19 00:10:07 +0000680}
681
Sean Callananb2814802016-02-12 21:11:25 +0000682static ConstString
683FindBestAlternateMangledName(const ConstString &demangled,
684 const lldb::LanguageType &lang_type,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000685 const SymbolContext &sym_ctx) {
686 CPlusPlusLanguage::MethodName cpp_name(demangled);
687 std::string scope_qualified_name = cpp_name.GetScopeQualifiedName();
Sean Callananb2814802016-02-12 21:11:25 +0000688
Kate Stoneb9c1b512016-09-06 20:57:50 +0000689 if (!scope_qualified_name.size())
690 return ConstString();
Sean Callananb2814802016-02-12 21:11:25 +0000691
Kate Stoneb9c1b512016-09-06 20:57:50 +0000692 if (!sym_ctx.module_sp)
693 return ConstString();
Sean Callananb2814802016-02-12 21:11:25 +0000694
Kate Stoneb9c1b512016-09-06 20:57:50 +0000695 SymbolVendor *sym_vendor = sym_ctx.module_sp->GetSymbolVendor();
696 if (!sym_vendor)
697 return ConstString();
Sean Callananb2814802016-02-12 21:11:25 +0000698
Kate Stoneb9c1b512016-09-06 20:57:50 +0000699 lldb_private::SymbolFile *sym_file = sym_vendor->GetSymbolFile();
700 if (!sym_file)
701 return ConstString();
Sean Callananb2814802016-02-12 21:11:25 +0000702
Kate Stoneb9c1b512016-09-06 20:57:50 +0000703 std::vector<ConstString> alternates;
704 sym_file->GetMangledNamesForFunction(scope_qualified_name, alternates);
Sean Callananb2814802016-02-12 21:11:25 +0000705
Kate Stoneb9c1b512016-09-06 20:57:50 +0000706 std::vector<ConstString> param_and_qual_matches;
707 std::vector<ConstString> param_matches;
708 for (size_t i = 0; i < alternates.size(); i++) {
709 ConstString alternate_mangled_name = alternates[i];
710 Mangled mangled(alternate_mangled_name, true);
711 ConstString demangled = mangled.GetDemangledName(lang_type);
Sean Callananb2814802016-02-12 21:11:25 +0000712
Kate Stoneb9c1b512016-09-06 20:57:50 +0000713 CPlusPlusLanguage::MethodName alternate_cpp_name(demangled);
714 if (!cpp_name.IsValid())
715 continue;
Sean Callananb2814802016-02-12 21:11:25 +0000716
Kate Stoneb9c1b512016-09-06 20:57:50 +0000717 if (alternate_cpp_name.GetArguments() == cpp_name.GetArguments()) {
718 if (alternate_cpp_name.GetQualifiers() == cpp_name.GetQualifiers())
719 param_and_qual_matches.push_back(alternate_mangled_name);
720 else
721 param_matches.push_back(alternate_mangled_name);
Sean Callananb2814802016-02-12 21:11:25 +0000722 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000723 }
Sean Callananb2814802016-02-12 21:11:25 +0000724
Kate Stoneb9c1b512016-09-06 20:57:50 +0000725 if (param_and_qual_matches.size())
726 return param_and_qual_matches[0]; // It is assumed that there will be only
727 // one!
728 else if (param_matches.size())
729 return param_matches[0]; // Return one of them as a best match
730 else
731 return ConstString();
Sean Callananb2814802016-02-12 21:11:25 +0000732}
733
Kate Stoneb9c1b512016-09-06 20:57:50 +0000734struct IRExecutionUnit::SearchSpec {
735 ConstString name;
736 uint32_t mask;
Sean Callananb2814802016-02-12 21:11:25 +0000737
Kate Stoneb9c1b512016-09-06 20:57:50 +0000738 SearchSpec(ConstString n, uint32_t m = lldb::eFunctionNameTypeFull)
739 : name(n), mask(m) {}
Sean Callananb2814802016-02-12 21:11:25 +0000740};
741
Kate Stoneb9c1b512016-09-06 20:57:50 +0000742void IRExecutionUnit::CollectCandidateCNames(
743 std::vector<IRExecutionUnit::SearchSpec> &C_specs,
744 const ConstString &name) {
745 if (m_strip_underscore && name.AsCString()[0] == '_')
746 C_specs.insert(C_specs.begin(), ConstString(&name.AsCString()[1]));
747 C_specs.push_back(SearchSpec(name));
Sean Callananb2814802016-02-12 21:11:25 +0000748}
749
Kate Stoneb9c1b512016-09-06 20:57:50 +0000750void IRExecutionUnit::CollectCandidateCPlusPlusNames(
751 std::vector<IRExecutionUnit::SearchSpec> &CPP_specs,
752 const std::vector<SearchSpec> &C_specs, const SymbolContext &sc) {
753 for (const SearchSpec &C_spec : C_specs) {
754 const ConstString &name = C_spec.name;
Sean Callananb2814802016-02-12 21:11:25 +0000755
Kate Stoneb9c1b512016-09-06 20:57:50 +0000756 if (CPlusPlusLanguage::IsCPPMangledName(name.GetCString())) {
757 Mangled mangled(name, true);
758 ConstString demangled =
759 mangled.GetDemangledName(lldb::eLanguageTypeC_plus_plus);
Chaoren Lin74a1fc62016-02-24 03:15:21 +0000760
Kate Stoneb9c1b512016-09-06 20:57:50 +0000761 if (demangled) {
762 ConstString best_alternate_mangled_name = FindBestAlternateMangledName(
763 demangled, lldb::eLanguageTypeC_plus_plus, sc);
Chaoren Lin74a1fc62016-02-24 03:15:21 +0000764
Kate Stoneb9c1b512016-09-06 20:57:50 +0000765 if (best_alternate_mangled_name) {
766 CPP_specs.push_back(best_alternate_mangled_name);
Sean Callananb2814802016-02-12 21:11:25 +0000767 }
Chaoren Lin74a1fc62016-02-24 03:15:21 +0000768
Kate Stoneb9c1b512016-09-06 20:57:50 +0000769 CPP_specs.push_back(SearchSpec(demangled, lldb::eFunctionNameTypeFull));
770 }
Sean Callananb2814802016-02-12 21:11:25 +0000771 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000772
Luke Drummondf5bb1d62016-12-19 17:22:44 +0000773 std::set<ConstString> alternates;
774 CPlusPlusLanguage::FindAlternateFunctionManglings(name, alternates);
775 CPP_specs.insert(CPP_specs.end(), alternates.begin(), alternates.end());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000776 }
Sean Callananb2814802016-02-12 21:11:25 +0000777}
778
Kate Stoneb9c1b512016-09-06 20:57:50 +0000779void IRExecutionUnit::CollectFallbackNames(
780 std::vector<SearchSpec> &fallback_specs,
781 const std::vector<SearchSpec> &C_specs) {
782 // As a last-ditch fallback, try the base name for C++ names. It's terrible,
783 // but the DWARF doesn't always encode "extern C" correctly.
784
785 for (const SearchSpec &C_spec : C_specs) {
786 const ConstString &name = C_spec.name;
787
788 if (CPlusPlusLanguage::IsCPPMangledName(name.GetCString())) {
789 Mangled mangled_name(name);
790 ConstString demangled_name =
791 mangled_name.GetDemangledName(lldb::eLanguageTypeC_plus_plus);
792 if (!demangled_name.IsEmpty()) {
793 const char *demangled_cstr = demangled_name.AsCString();
794 const char *lparen_loc = strchr(demangled_cstr, '(');
795 if (lparen_loc) {
796 llvm::StringRef base_name(demangled_cstr,
797 lparen_loc - demangled_cstr);
798 fallback_specs.push_back(ConstString(base_name));
Sean Callanan34ab28a2016-06-02 17:59:47 +0000799 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000800 }
Sean Callanan34ab28a2016-06-02 17:59:47 +0000801 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000802 }
Sean Callanan34ab28a2016-06-02 17:59:47 +0000803}
804
Kate Stoneb9c1b512016-09-06 20:57:50 +0000805lldb::addr_t IRExecutionUnit::FindInSymbols(
806 const std::vector<IRExecutionUnit::SearchSpec> &specs,
807 const lldb_private::SymbolContext &sc) {
808 Target *target = sc.target_sp.get();
Sean Callanan34ab28a2016-06-02 17:59:47 +0000809
Kate Stoneb9c1b512016-09-06 20:57:50 +0000810 if (!target) {
811 // we shouldn't be doing any symbol lookup at all without a target
812 return LLDB_INVALID_ADDRESS;
813 }
Sean Callananfed0e7582016-02-23 23:09:06 +0000814
Kate Stoneb9c1b512016-09-06 20:57:50 +0000815 for (const SearchSpec &spec : specs) {
816 SymbolContextList sc_list;
Sean Callananfed0e7582016-02-23 23:09:06 +0000817
Kate Stoneb9c1b512016-09-06 20:57:50 +0000818 lldb::addr_t best_internal_load_address = LLDB_INVALID_ADDRESS;
Sean Callananfed0e7582016-02-23 23:09:06 +0000819
Kate Stoneb9c1b512016-09-06 20:57:50 +0000820 std::function<bool(lldb::addr_t &, SymbolContextList &,
821 const lldb_private::SymbolContext &)>
822 get_external_load_address = [&best_internal_load_address, target](
823 lldb::addr_t &load_address, SymbolContextList &sc_list,
824 const lldb_private::SymbolContext &sc) -> lldb::addr_t {
825 load_address = LLDB_INVALID_ADDRESS;
Sean Callananfed0e7582016-02-23 23:09:06 +0000826
Kate Stoneb9c1b512016-09-06 20:57:50 +0000827 for (size_t si = 0, se = sc_list.GetSize(); si < se; ++si) {
828 SymbolContext candidate_sc;
829
830 sc_list.GetContextAtIndex(si, candidate_sc);
831
832 const bool is_external =
833 (candidate_sc.function) ||
834 (candidate_sc.symbol && candidate_sc.symbol->IsExternal());
835 if (candidate_sc.symbol) {
836 load_address = candidate_sc.symbol->ResolveCallableAddress(*target);
837
838 if (load_address == LLDB_INVALID_ADDRESS) {
839 if (target->GetProcessSP())
840 load_address =
841 candidate_sc.symbol->GetAddress().GetLoadAddress(target);
842 else
843 load_address = candidate_sc.symbol->GetAddress().GetFileAddress();
844 }
845 }
846
847 if (load_address == LLDB_INVALID_ADDRESS && candidate_sc.function) {
848 if (target->GetProcessSP())
849 load_address = candidate_sc.function->GetAddressRange()
850 .GetBaseAddress()
851 .GetLoadAddress(target);
852 else
853 load_address = candidate_sc.function->GetAddressRange()
854 .GetBaseAddress()
855 .GetFileAddress();
856 }
857
858 if (load_address != LLDB_INVALID_ADDRESS) {
859 if (is_external) {
860 return true;
861 } else if (best_internal_load_address == LLDB_INVALID_ADDRESS) {
862 best_internal_load_address = load_address;
Sean Callananfed0e7582016-02-23 23:09:06 +0000863 load_address = LLDB_INVALID_ADDRESS;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000864 }
865 }
866 }
Sean Callananfed0e7582016-02-23 23:09:06 +0000867
Kate Stoneb9c1b512016-09-06 20:57:50 +0000868 return false;
869 };
Sean Callananfed0e7582016-02-23 23:09:06 +0000870
Kate Stoneb9c1b512016-09-06 20:57:50 +0000871 if (sc.module_sp) {
872 sc.module_sp->FindFunctions(spec.name, NULL, spec.mask,
873 true, // include_symbols
874 false, // include_inlines
875 true, // append
876 sc_list);
877 }
Sean Callananfed0e7582016-02-23 23:09:06 +0000878
Kate Stoneb9c1b512016-09-06 20:57:50 +0000879 lldb::addr_t load_address = LLDB_INVALID_ADDRESS;
Ted Woodwardeee554d2016-03-09 22:05:17 +0000880
Kate Stoneb9c1b512016-09-06 20:57:50 +0000881 if (get_external_load_address(load_address, sc_list, sc)) {
882 return load_address;
883 } else {
884 sc_list.Clear();
885 }
886
887 if (sc_list.GetSize() == 0 && sc.target_sp) {
888 sc.target_sp->GetImages().FindFunctions(spec.name, spec.mask,
889 true, // include_symbols
890 false, // include_inlines
891 true, // append
892 sc_list);
893 }
894
895 if (get_external_load_address(load_address, sc_list, sc)) {
896 return load_address;
897 } else {
898 sc_list.Clear();
899 }
900
901 if (sc_list.GetSize() == 0 && sc.target_sp) {
902 sc.target_sp->GetImages().FindSymbolsWithNameAndType(
903 spec.name, lldb::eSymbolTypeAny, sc_list);
904 }
905
906 if (get_external_load_address(load_address, sc_list, sc)) {
907 return load_address;
908 }
909 // if there are any searches we try after this, add an sc_list.Clear() in an
910 // "else" clause here
911
912 if (best_internal_load_address != LLDB_INVALID_ADDRESS) {
913 return best_internal_load_address;
914 }
915 }
916
917 return LLDB_INVALID_ADDRESS;
918}
919
920lldb::addr_t
921IRExecutionUnit::FindInRuntimes(const std::vector<SearchSpec> &specs,
922 const lldb_private::SymbolContext &sc) {
923 lldb::TargetSP target_sp = sc.target_sp;
924
925 if (!target_sp) {
926 return LLDB_INVALID_ADDRESS;
927 }
928
929 lldb::ProcessSP process_sp = sc.target_sp->GetProcessSP();
930
931 if (!process_sp) {
932 return LLDB_INVALID_ADDRESS;
933 }
934
935 ObjCLanguageRuntime *runtime = process_sp->GetObjCLanguageRuntime();
936
937 if (runtime) {
938 for (const SearchSpec &spec : specs) {
939 lldb::addr_t symbol_load_addr = runtime->LookupRuntimeSymbol(spec.name);
940
941 if (symbol_load_addr != LLDB_INVALID_ADDRESS)
942 return symbol_load_addr;
943 }
944 }
945
946 return LLDB_INVALID_ADDRESS;
947}
948
949lldb::addr_t IRExecutionUnit::FindInUserDefinedSymbols(
950 const std::vector<SearchSpec> &specs,
951 const lldb_private::SymbolContext &sc) {
952 lldb::TargetSP target_sp = sc.target_sp;
953
954 for (const SearchSpec &spec : specs) {
955 lldb::addr_t symbol_load_addr = target_sp->GetPersistentSymbol(spec.name);
956
957 if (symbol_load_addr != LLDB_INVALID_ADDRESS)
958 return symbol_load_addr;
959 }
960
961 return LLDB_INVALID_ADDRESS;
962}
963
964lldb::addr_t
965IRExecutionUnit::FindSymbol(const lldb_private::ConstString &name) {
966 std::vector<SearchSpec> candidate_C_names;
967 std::vector<SearchSpec> candidate_CPlusPlus_names;
968
969 CollectCandidateCNames(candidate_C_names, name);
970
971 lldb::addr_t ret = FindInSymbols(candidate_C_names, m_sym_ctx);
972 if (ret == LLDB_INVALID_ADDRESS)
973 ret = FindInRuntimes(candidate_C_names, m_sym_ctx);
974
975 if (ret == LLDB_INVALID_ADDRESS)
976 ret = FindInUserDefinedSymbols(candidate_C_names, m_sym_ctx);
977
978 if (ret == LLDB_INVALID_ADDRESS) {
979 CollectCandidateCPlusPlusNames(candidate_CPlusPlus_names, candidate_C_names,
980 m_sym_ctx);
981 ret = FindInSymbols(candidate_CPlusPlus_names, m_sym_ctx);
982 }
983
984 if (ret == LLDB_INVALID_ADDRESS) {
985 std::vector<SearchSpec> candidate_fallback_names;
986
987 CollectFallbackNames(candidate_fallback_names, candidate_C_names);
988 ret = FindInSymbols(candidate_fallback_names, m_sym_ctx);
989 }
990
991 return ret;
992}
993
994void IRExecutionUnit::GetStaticInitializers(
995 std::vector<lldb::addr_t> &static_initializers) {
996 if (llvm::GlobalVariable *global_ctors =
997 m_module->getNamedGlobal("llvm.global_ctors")) {
998 if (llvm::ConstantArray *ctor_array = llvm::dyn_cast<llvm::ConstantArray>(
999 global_ctors->getInitializer())) {
1000 for (llvm::Use &ctor_use : ctor_array->operands()) {
1001 if (llvm::ConstantStruct *ctor_struct =
1002 llvm::dyn_cast<llvm::ConstantStruct>(ctor_use)) {
1003 lldbassert(ctor_struct->getNumOperands() ==
1004 3); // this is standardized
1005 if (llvm::Function *ctor_function =
1006 llvm::dyn_cast<llvm::Function>(ctor_struct->getOperand(1))) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001007 ConstString ctor_function_name_cs(ctor_function->getName().str());
1008
1009 for (JittedFunction &jitted_function : m_jitted_functions) {
1010 if (ctor_function_name_cs == jitted_function.m_name) {
1011 if (jitted_function.m_remote_addr != LLDB_INVALID_ADDRESS) {
1012 static_initializers.push_back(jitted_function.m_remote_addr);
Ted Woodwardeee554d2016-03-09 22:05:17 +00001013 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001014 break;
1015 }
Sean Callananfed0e7582016-02-23 23:09:06 +00001016 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001017 }
Sean Callananb2814802016-02-12 21:11:25 +00001018 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001019 }
Sean Callananb2814802016-02-12 21:11:25 +00001020 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001021 }
Sean Callananbd4dc692016-03-21 22:23:38 +00001022}
1023
Jim Ingham27e5fe82015-01-27 18:03:05 +00001024uint64_t
Kate Stoneb9c1b512016-09-06 20:57:50 +00001025IRExecutionUnit::MemoryManager::getSymbolAddress(const std::string &Name) {
1026 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
Greg Claytond6171a72015-07-02 16:43:49 +00001027
Kate Stoneb9c1b512016-09-06 20:57:50 +00001028 ConstString name_cs(Name.c_str());
Chaoren Lin74a1fc62016-02-24 03:15:21 +00001029
Kate Stoneb9c1b512016-09-06 20:57:50 +00001030 lldb::addr_t ret = m_parent.FindSymbol(name_cs);
Chaoren Lin74a1fc62016-02-24 03:15:21 +00001031
Kate Stoneb9c1b512016-09-06 20:57:50 +00001032 if (ret == LLDB_INVALID_ADDRESS) {
1033 if (log)
1034 log->Printf(
1035 "IRExecutionUnit::getSymbolAddress(Name=\"%s\") = <not found>",
1036 Name.c_str());
Sean Callananb2814802016-02-12 21:11:25 +00001037
Kate Stoneb9c1b512016-09-06 20:57:50 +00001038 m_parent.ReportSymbolLookupError(name_cs);
1039 return 0xbad0bad0;
1040 } else {
1041 if (log)
1042 log->Printf("IRExecutionUnit::getSymbolAddress(Name=\"%s\") = %" PRIx64,
1043 Name.c_str(), ret);
1044 return ret;
1045 }
Jim Ingham27e5fe82015-01-27 18:03:05 +00001046}
1047
Kate Stoneb9c1b512016-09-06 20:57:50 +00001048void *IRExecutionUnit::MemoryManager::getPointerToNamedFunction(
1049 const std::string &Name, bool AbortOnFailure) {
1050 assert(sizeof(void *) == 8);
Chaoren Lin74a1fc62016-02-24 03:15:21 +00001051
Kate Stoneb9c1b512016-09-06 20:57:50 +00001052 return (void *)getSymbolAddress(Name);
Jim Ingham27e5fe82015-01-27 18:03:05 +00001053}
1054
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001055lldb::addr_t
Kate Stoneb9c1b512016-09-06 20:57:50 +00001056IRExecutionUnit::GetRemoteAddressForLocal(lldb::addr_t local_address) {
1057 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
Sean Callananffae9442013-06-27 01:42:47 +00001058
Kate Stoneb9c1b512016-09-06 20:57:50 +00001059 for (AllocationRecord &record : m_records) {
1060 if (local_address >= record.m_host_address &&
1061 local_address < record.m_host_address + record.m_size) {
1062 if (record.m_process_address == LLDB_INVALID_ADDRESS)
1063 return LLDB_INVALID_ADDRESS;
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +00001064
Kate Stoneb9c1b512016-09-06 20:57:50 +00001065 lldb::addr_t ret =
1066 record.m_process_address + (local_address - record.m_host_address);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +00001067
Kate Stoneb9c1b512016-09-06 20:57:50 +00001068 if (log) {
1069 log->Printf(
1070 "IRExecutionUnit::GetRemoteAddressForLocal() found 0x%" PRIx64
1071 " in [0x%" PRIx64 "..0x%" PRIx64 "], and returned 0x%" PRIx64
1072 " from [0x%" PRIx64 "..0x%" PRIx64 "].",
1073 local_address, (uint64_t)record.m_host_address,
1074 (uint64_t)record.m_host_address + (uint64_t)record.m_size, ret,
1075 record.m_process_address, record.m_process_address + record.m_size);
1076 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +00001077
Kate Stoneb9c1b512016-09-06 20:57:50 +00001078 return ret;
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001079 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001080 }
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001081
Kate Stoneb9c1b512016-09-06 20:57:50 +00001082 return LLDB_INVALID_ADDRESS;
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001083}
1084
1085IRExecutionUnit::AddrRange
Kate Stoneb9c1b512016-09-06 20:57:50 +00001086IRExecutionUnit::GetRemoteRangeForLocal(lldb::addr_t local_address) {
1087 for (AllocationRecord &record : m_records) {
1088 if (local_address >= record.m_host_address &&
1089 local_address < record.m_host_address + record.m_size) {
1090 if (record.m_process_address == LLDB_INVALID_ADDRESS)
1091 return AddrRange(0, 0);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +00001092
Kate Stoneb9c1b512016-09-06 20:57:50 +00001093 return AddrRange(record.m_process_address, record.m_size);
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001094 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001095 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +00001096
Kate Stoneb9c1b512016-09-06 20:57:50 +00001097 return AddrRange(0, 0);
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001098}
1099
Kate Stoneb9c1b512016-09-06 20:57:50 +00001100bool IRExecutionUnit::CommitOneAllocation(lldb::ProcessSP &process_sp,
Zachary Turner97206d52017-05-12 04:51:55 +00001101 Status &error,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001102 AllocationRecord &record) {
1103 if (record.m_process_address != LLDB_INVALID_ADDRESS) {
1104 return true;
1105 }
1106
1107 switch (record.m_sect_type) {
1108 case lldb::eSectionTypeInvalid:
1109 case lldb::eSectionTypeDWARFDebugAbbrev:
1110 case lldb::eSectionTypeDWARFDebugAddr:
1111 case lldb::eSectionTypeDWARFDebugAranges:
Tamas Berghammer963ce482017-08-25 13:56:14 +00001112 case lldb::eSectionTypeDWARFDebugCuIndex:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001113 case lldb::eSectionTypeDWARFDebugFrame:
1114 case lldb::eSectionTypeDWARFDebugInfo:
1115 case lldb::eSectionTypeDWARFDebugLine:
1116 case lldb::eSectionTypeDWARFDebugLoc:
1117 case lldb::eSectionTypeDWARFDebugMacInfo:
1118 case lldb::eSectionTypeDWARFDebugPubNames:
1119 case lldb::eSectionTypeDWARFDebugPubTypes:
1120 case lldb::eSectionTypeDWARFDebugRanges:
1121 case lldb::eSectionTypeDWARFDebugStr:
1122 case lldb::eSectionTypeDWARFDebugStrOffsets:
1123 case lldb::eSectionTypeDWARFAppleNames:
1124 case lldb::eSectionTypeDWARFAppleTypes:
1125 case lldb::eSectionTypeDWARFAppleNamespaces:
1126 case lldb::eSectionTypeDWARFAppleObjC:
1127 error.Clear();
1128 break;
1129 default:
1130 const bool zero_memory = false;
1131 record.m_process_address =
1132 Malloc(record.m_size, record.m_alignment, record.m_permissions,
1133 eAllocationPolicyProcessOnly, zero_memory, error);
1134 break;
1135 }
1136
1137 return error.Success();
1138}
1139
1140bool IRExecutionUnit::CommitAllocations(lldb::ProcessSP &process_sp) {
1141 bool ret = true;
1142
Zachary Turner97206d52017-05-12 04:51:55 +00001143 lldb_private::Status err;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001144
1145 for (AllocationRecord &record : m_records) {
1146 ret = CommitOneAllocation(process_sp, err, record);
1147
1148 if (!ret) {
1149 break;
Sean Callananbd4dc692016-03-21 22:23:38 +00001150 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001151 }
1152
1153 if (!ret) {
1154 for (AllocationRecord &record : m_records) {
1155 if (record.m_process_address != LLDB_INVALID_ADDRESS) {
1156 Free(record.m_process_address, err);
1157 record.m_process_address = LLDB_INVALID_ADDRESS;
1158 }
Sean Callananbd4dc692016-03-21 22:23:38 +00001159 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001160 }
1161
1162 return ret;
Sean Callananbd4dc692016-03-21 22:23:38 +00001163}
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +00001164
Kate Stoneb9c1b512016-09-06 20:57:50 +00001165void IRExecutionUnit::ReportAllocations(llvm::ExecutionEngine &engine) {
1166 m_reported_allocations = true;
Sean Callananbd4dc692016-03-21 22:23:38 +00001167
Kate Stoneb9c1b512016-09-06 20:57:50 +00001168 for (AllocationRecord &record : m_records) {
1169 if (record.m_process_address == LLDB_INVALID_ADDRESS)
1170 continue;
Sean Callananbd4dc692016-03-21 22:23:38 +00001171
Kate Stoneb9c1b512016-09-06 20:57:50 +00001172 if (record.m_section_id == eSectionIDInvalid)
1173 continue;
1174
1175 engine.mapSectionAddress((void *)record.m_host_address,
1176 record.m_process_address);
1177 }
1178
1179 // Trigger re-application of relocations.
1180 engine.finalizeObject();
1181}
1182
1183bool IRExecutionUnit::WriteData(lldb::ProcessSP &process_sp) {
1184 bool wrote_something = false;
1185 for (AllocationRecord &record : m_records) {
1186 if (record.m_process_address != LLDB_INVALID_ADDRESS) {
Zachary Turner97206d52017-05-12 04:51:55 +00001187 lldb_private::Status err;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001188 WriteMemory(record.m_process_address, (uint8_t *)record.m_host_address,
1189 record.m_size, err);
1190 if (err.Success())
1191 wrote_something = true;
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001192 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001193 }
1194 return wrote_something;
1195}
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +00001196
Kate Stoneb9c1b512016-09-06 20:57:50 +00001197void IRExecutionUnit::AllocationRecord::dump(Log *log) {
1198 if (!log)
1199 return;
1200
1201 log->Printf("[0x%llx+0x%llx]->0x%llx (alignment %d, section ID %d, name %s)",
1202 (unsigned long long)m_host_address, (unsigned long long)m_size,
1203 (unsigned long long)m_process_address, (unsigned)m_alignment,
1204 (unsigned)m_section_id, m_name.c_str());
1205}
1206
1207lldb::ByteOrder IRExecutionUnit::GetByteOrder() const {
1208 ExecutionContext exe_ctx(GetBestExecutionContextScope());
1209 return exe_ctx.GetByteOrder();
1210}
1211
1212uint32_t IRExecutionUnit::GetAddressByteSize() const {
1213 ExecutionContext exe_ctx(GetBestExecutionContextScope());
1214 return exe_ctx.GetAddressByteSize();
1215}
1216
1217void IRExecutionUnit::PopulateSymtab(lldb_private::ObjectFile *obj_file,
1218 lldb_private::Symtab &symtab) {
1219 // No symbols yet...
1220}
1221
1222void IRExecutionUnit::PopulateSectionList(
1223 lldb_private::ObjectFile *obj_file,
1224 lldb_private::SectionList &section_list) {
1225 for (AllocationRecord &record : m_records) {
1226 if (record.m_size > 0) {
1227 lldb::SectionSP section_sp(new lldb_private::Section(
1228 obj_file->GetModule(), obj_file, record.m_section_id,
1229 ConstString(record.m_name), record.m_sect_type,
1230 record.m_process_address, record.m_size,
1231 record.m_host_address, // file_offset (which is the host address for
1232 // the data)
1233 record.m_size, // file_size
1234 0,
1235 record.m_permissions)); // flags
1236 section_list.AddSection(section_sp);
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001237 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001238 }
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001239}
1240
Kate Stoneb9c1b512016-09-06 20:57:50 +00001241bool IRExecutionUnit::GetArchitecture(lldb_private::ArchSpec &arch) {
1242 ExecutionContext exe_ctx(GetBestExecutionContextScope());
1243 Target *target = exe_ctx.GetTargetPtr();
1244 if (target)
1245 arch = target->GetArchitecture();
1246 else
1247 arch.Clear();
1248 return arch.IsValid();
1249}
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +00001250
Kate Stoneb9c1b512016-09-06 20:57:50 +00001251lldb::ModuleSP IRExecutionUnit::GetJITModule() {
1252 ExecutionContext exe_ctx(GetBestExecutionContextScope());
1253 Target *target = exe_ctx.GetTargetPtr();
1254 if (target) {
1255 lldb::ModuleSP jit_module_sp = lldb_private::Module::CreateJITModule(
1256 std::static_pointer_cast<lldb_private::ObjectFileJITDelegate>(
1257 shared_from_this()));
1258 if (jit_module_sp) {
1259 bool changed = false;
1260 jit_module_sp->SetLoadAddress(*target, 0, true, changed);
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001261 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001262 return jit_module_sp;
1263 }
1264 return lldb::ModuleSP();
Greg Clayton23f8c952014-03-24 23:10:19 +00001265}