blob: 9ad2b33ce71edbbe353ff2855bfa0f608f14acb6 [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
Sean Callanan8dfb68e2013-03-19 00:10:07 +000018#include "lldb/Core/DataBufferHeap.h"
19#include "lldb/Core/DataExtractor.h"
Jason Molendaaff1b352014-10-10 23:07:36 +000020#include "lldb/Core/Debugger.h"
Sean Callanan8dfb68e2013-03-19 00:10:07 +000021#include "lldb/Core/Disassembler.h"
22#include "lldb/Core/Log.h"
Greg Clayton23f8c952014-03-24 23:10:19 +000023#include "lldb/Core/Module.h"
24#include "lldb/Core/Section.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000025#include "lldb/Expression/IRExecutionUnit.h"
Sean Callananb2814802016-02-12 21:11:25 +000026#include "lldb/Symbol/CompileUnit.h"
Zachary Turnera78bd7f2015-03-03 23:11:11 +000027#include "lldb/Symbol/SymbolContext.h"
Sean Callananb2814802016-02-12 21:11:25 +000028#include "lldb/Symbol/SymbolFile.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000029#include "lldb/Symbol/SymbolVendor.h"
Sean Callanan8dfb68e2013-03-19 00:10:07 +000030#include "lldb/Target/ExecutionContext.h"
Zachary Turnera78bd7f2015-03-03 23:11:11 +000031#include "lldb/Target/ObjCLanguageRuntime.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000032#include "lldb/Target/Target.h"
Sean Callananbd4dc692016-03-21 22:23:38 +000033#include "lldb/Utility/LLDBAssert.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,
53 Error &error) {
54 const bool zero_memory = false;
55 lldb::addr_t allocation_process_addr =
56 Malloc(size, 8, lldb::ePermissionsWritable | lldb::ePermissionsReadable,
57 eAllocationPolicyMirror, zero_memory, error);
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()) {
Sean Callanan5a1af4e2013-04-05 02:22:57 +000065 Error 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);
Sean Callanan8dfb68e2013-03-19 00:10:07 +000074 Error 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
93 Error err;
94
95 Free(allocation, err);
96}
97
98Error IRExecutionUnit::DisassembleFunction(Stream &stream,
99 lldb::ProcessSP &process_wp) {
100 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
101
102 ExecutionContext exe_ctx(process_wp);
103
104 Error ret;
105
106 ret.Clear();
107
108 lldb::addr_t func_local_addr = LLDB_INVALID_ADDRESS;
109 lldb::addr_t func_remote_addr = LLDB_INVALID_ADDRESS;
110
111 for (JittedFunction &function : m_jitted_functions) {
112 if (function.m_name == m_name) {
113 func_local_addr = function.m_local_addr;
114 func_remote_addr = function.m_remote_addr;
115 }
116 }
117
118 if (func_local_addr == LLDB_INVALID_ADDRESS) {
119 ret.SetErrorToGenericError();
120 ret.SetErrorStringWithFormat("Couldn't find function %s for disassembly",
121 m_name.AsCString());
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();
155 Error err;
156 process->ReadMemory(func_remote_addr, buffer_sp->GetBytes(),
157 buffer_sp->GetByteSize(), err);
158
159 if (!err.Success()) {
160 ret.SetErrorToGenericError();
161 ret.SetErrorStringWithFormat("Couldn't read from process: %s",
162 err.AsCString("unknown error"));
163 return ret;
164 }
165
166 ArchSpec arch(target->GetArchitecture());
167
168 const char *plugin_name = NULL;
169 const char *flavor_string = NULL;
170 lldb::DisassemblerSP disassembler_sp =
171 Disassembler::FindPlugin(arch, flavor_string, plugin_name);
172
173 if (!disassembler_sp) {
174 ret.SetErrorToGenericError();
175 ret.SetErrorStringWithFormat(
176 "Unable to find disassembler plug-in for %s architecture.",
177 arch.GetArchitectureName());
178 return ret;
179 }
180
181 if (!process) {
182 ret.SetErrorToGenericError();
183 ret.SetErrorString("Couldn't find the process");
184 return ret;
185 }
186
187 DataExtractor extractor(buffer_sp, process->GetByteOrder(),
188 target->GetArchitecture().GetAddressByteSize());
189
190 if (log) {
191 log->Printf("Function data has contents:");
192 extractor.PutToLog(log, 0, extractor.GetByteSize(), func_remote_addr, 16,
193 DataExtractor::TypeUInt8);
194 }
195
196 disassembler_sp->DecodeInstructions(Address(func_remote_addr), extractor, 0,
197 UINT32_MAX, false, false);
198
199 InstructionList &instruction_list = disassembler_sp->GetInstructionList();
200 instruction_list.Dump(&stream, true, true, &exe_ctx);
201 return ret;
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) {
206 Error *err = static_cast<Error *>(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
Kate Stoneb9c1b512016-09-06 20:57:50 +0000219void IRExecutionUnit::GetRunnableInfo(Error &error, lldb::addr_t &func_addr,
220 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;
263 llvm::CodeModel::Model codeModel;
264
265 if (triple.isOSBinFormatELF()) {
266 relocModel = llvm::Reloc::Static;
267 } else {
268 relocModel = llvm::Reloc::PIC_;
269 }
270
271 // This will be small for 32-bit and large for 64-bit.
272 codeModel = llvm::CodeModel::JITDefault;
273
274 m_module_ap->getContext().setInlineAsmDiagnosticHandler(ReportInlineAsmError,
275 &error);
276
277 llvm::EngineBuilder builder(std::move(m_module_ap));
278
279 builder.setEngineKind(llvm::EngineKind::JIT)
280 .setErrorStr(&error_string)
281 .setRelocationModel(relocModel)
282 .setMCJITMemoryManager(
283 std::unique_ptr<MemoryManager>(new MemoryManager(*this)))
284 .setCodeModel(codeModel)
285 .setOptLevel(llvm::CodeGenOpt::Less)
286 .setUseOrcMCJITReplacement(true);
287
288 llvm::StringRef mArch;
289 llvm::StringRef mCPU;
290 llvm::SmallVector<std::string, 0> mAttrs;
291
292 for (std::string &feature : m_cpu_features)
293 mAttrs.push_back(feature);
294
295 llvm::TargetMachine *target_machine =
296 builder.selectTarget(triple, mArch, mCPU, mAttrs);
297
298 m_execution_engine_ap.reset(builder.create(target_machine));
299
300 m_strip_underscore =
301 (m_execution_engine_ap->getDataLayout().getGlobalPrefix() == '_');
302
303 if (!m_execution_engine_ap.get()) {
304 error.SetErrorToGenericError();
305 error.SetErrorStringWithFormat("Couldn't JIT the function: %s",
306 error_string.c_str());
307 return;
308 }
309
Sean Callanan5deb06e2016-09-26 20:18:51 +0000310 class ObjectDumper : public llvm::ObjectCache {
311 public:
312 void notifyObjectCompiled(const llvm::Module *module,
313 llvm::MemoryBufferRef object) override {
314 int fd = 0;
315 llvm::SmallVector<char, 256> result_path;
316 std::string object_name_model =
317 "jit-object-" + module->getModuleIdentifier() + "-%%%.o";
318 (void)llvm::sys::fs::createUniqueFile(object_name_model, fd, result_path);
319 llvm::raw_fd_ostream fds(fd, true);
320 fds.write(object.getBufferStart(), object.getBufferSize());
321 }
322
323 std::unique_ptr<llvm::MemoryBuffer>
324 getObject(const llvm::Module *module) override {
325 // Return nothing - we're just abusing the object-cache mechanism to dump
326 // objects.
327 return nullptr;
328 }
329 };
330
331 if (process_sp->GetTarget().GetEnableSaveObjects()) {
332 m_object_cache_ap = llvm::make_unique<ObjectDumper>();
333 m_execution_engine_ap->setObjectCache(m_object_cache_ap.get());
334 }
335
Kate Stoneb9c1b512016-09-06 20:57:50 +0000336 // Make sure we see all sections, including ones that don't have
337 // relocations...
338 m_execution_engine_ap->setProcessAllSections(true);
339
340 m_execution_engine_ap->DisableLazyCompilation();
341
342 for (llvm::Function &function : *m_module) {
343 if (function.isDeclaration() || function.hasPrivateLinkage())
344 continue;
345
346 const bool external =
347 function.hasExternalLinkage() || function.hasLinkOnceODRLinkage();
348
349 void *fun_ptr = m_execution_engine_ap->getPointerToFunction(&function);
350
351 if (!error.Success()) {
352 // We got an error through our callback!
353 return;
Greg Clayton23f8c952014-03-24 23:10:19 +0000354 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000355
Kate Stoneb9c1b512016-09-06 20:57:50 +0000356 if (!fun_ptr) {
357 error.SetErrorToGenericError();
358 error.SetErrorStringWithFormat(
359 "'%s' was in the JITted module but wasn't lowered",
360 function.getName().str().c_str());
361 return;
362 }
363 m_jitted_functions.push_back(JittedFunction(
364 function.getName().str().c_str(), external, (lldb::addr_t)fun_ptr));
365 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000366
Kate Stoneb9c1b512016-09-06 20:57:50 +0000367 CommitAllocations(process_sp);
368 ReportAllocations(*m_execution_engine_ap);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000369
Kate Stoneb9c1b512016-09-06 20:57:50 +0000370 // We have to do this after calling ReportAllocations because for the MCJIT,
371 // getGlobalValueAddress
372 // will cause the JIT to perform all relocations. That can only be done once,
373 // and has to happen
374 // after we do the remapping from local -> remote.
375 // That means we don't know the local address of the Variables, but we don't
376 // need that for anything,
377 // so that's okay.
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000378
Kate Stoneb9c1b512016-09-06 20:57:50 +0000379 std::function<void(llvm::GlobalValue &)> RegisterOneValue = [this](
380 llvm::GlobalValue &val) {
381 if (val.hasExternalLinkage() && !val.isDeclaration()) {
382 uint64_t var_ptr_addr =
383 m_execution_engine_ap->getGlobalValueAddress(val.getName().str());
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000384
Kate Stoneb9c1b512016-09-06 20:57:50 +0000385 lldb::addr_t remote_addr = GetRemoteAddressForLocal(var_ptr_addr);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000386
Kate Stoneb9c1b512016-09-06 20:57:50 +0000387 // This is a really unfortunae API that sometimes returns local addresses
388 // and sometimes returns remote addresses, based on whether
389 // the variable was relocated during ReportAllocations or not.
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000390
Kate Stoneb9c1b512016-09-06 20:57:50 +0000391 if (remote_addr == LLDB_INVALID_ADDRESS) {
392 remote_addr = var_ptr_addr;
393 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000394
Kate Stoneb9c1b512016-09-06 20:57:50 +0000395 if (var_ptr_addr != 0)
396 m_jitted_global_variables.push_back(JittedGlobalVariable(
397 val.getName().str().c_str(), LLDB_INVALID_ADDRESS, remote_addr));
398 }
399 };
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000400
Kate Stoneb9c1b512016-09-06 20:57:50 +0000401 for (llvm::GlobalVariable &global_var : m_module->getGlobalList()) {
402 RegisterOneValue(global_var);
403 }
404
405 for (llvm::GlobalAlias &global_alias : m_module->getAliasList()) {
406 RegisterOneValue(global_alias);
407 }
408
409 WriteData(process_sp);
410
411 if (m_failed_lookups.size()) {
412 StreamString ss;
413
414 ss.PutCString("Couldn't lookup symbols:\n");
415
416 bool emitNewLine = false;
417
418 for (const ConstString &failed_lookup : m_failed_lookups) {
419 if (emitNewLine)
420 ss.PutCString("\n");
421 emitNewLine = true;
422 ss.PutCString(" ");
423 ss.PutCString(Mangled(failed_lookup)
424 .GetDemangledName(lldb::eLanguageTypeObjC_plus_plus)
425 .AsCString());
426 }
427
428 m_failed_lookups.clear();
429
Zachary Turnerc1564272016-11-16 21:15:24 +0000430 error.SetErrorString(ss.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000431
432 return;
433 }
434
435 m_function_load_addr = LLDB_INVALID_ADDRESS;
436 m_function_end_load_addr = LLDB_INVALID_ADDRESS;
437
438 for (JittedFunction &jitted_function : m_jitted_functions) {
439 jitted_function.m_remote_addr =
440 GetRemoteAddressForLocal(jitted_function.m_local_addr);
441
442 if (!m_name.IsEmpty() && jitted_function.m_name == m_name) {
443 AddrRange func_range =
444 GetRemoteRangeForLocal(jitted_function.m_local_addr);
445 m_function_end_load_addr = func_range.first + func_range.second;
446 m_function_load_addr = jitted_function.m_remote_addr;
447 }
448 }
449
450 if (log) {
451 log->Printf("Code can be run in the target.");
452
453 StreamString disassembly_stream;
454
455 Error err = DisassembleFunction(disassembly_stream, process_sp);
456
457 if (!err.Success()) {
458 log->Printf("Couldn't disassemble function : %s",
459 err.AsCString("unknown error"));
460 } else {
461 log->Printf("Function disassembly:\n%s", disassembly_stream.GetData());
462 }
463
464 log->Printf("Sections: ");
465 for (AllocationRecord &record : m_records) {
466 if (record.m_process_address != LLDB_INVALID_ADDRESS) {
467 record.dump(log);
468
469 DataBufferHeap my_buffer(record.m_size, 0);
470 Error err;
471 ReadMemory(my_buffer.GetBytes(), record.m_process_address,
472 record.m_size, err);
473
474 if (err.Success()) {
475 DataExtractor my_extractor(my_buffer.GetBytes(),
476 my_buffer.GetByteSize(),
477 lldb::eByteOrderBig, 8);
478 my_extractor.PutToLog(log, 0, my_buffer.GetByteSize(),
479 record.m_process_address, 16,
480 DataExtractor::TypeUInt8);
Greg Clayton23f8c952014-03-24 23:10:19 +0000481 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000482 } else {
483 record.dump(log);
484
485 DataExtractor my_extractor((const void *)record.m_host_address,
486 record.m_size, lldb::eByteOrderBig, 8);
487 my_extractor.PutToLog(log, 0, record.m_size, record.m_host_address, 16,
488 DataExtractor::TypeUInt8);
489 }
490 }
491 }
492
493 func_addr = m_function_load_addr;
494 func_end = m_function_end_load_addr;
495
496 return;
497}
498
499IRExecutionUnit::~IRExecutionUnit() {
500 m_module_ap.reset();
501 m_execution_engine_ap.reset();
502 m_context_ap.reset();
503}
504
505IRExecutionUnit::MemoryManager::MemoryManager(IRExecutionUnit &parent)
506 : m_default_mm_ap(new llvm::SectionMemoryManager()), m_parent(parent) {}
507
508IRExecutionUnit::MemoryManager::~MemoryManager() {}
509
510lldb::SectionType IRExecutionUnit::GetSectionTypeFromSectionName(
511 const llvm::StringRef &name, IRExecutionUnit::AllocationKind alloc_kind) {
512 lldb::SectionType sect_type = lldb::eSectionTypeCode;
513 switch (alloc_kind) {
514 case AllocationKind::Stub:
515 sect_type = lldb::eSectionTypeCode;
516 break;
517 case AllocationKind::Code:
518 sect_type = lldb::eSectionTypeCode;
519 break;
520 case AllocationKind::Data:
521 sect_type = lldb::eSectionTypeData;
522 break;
523 case AllocationKind::Global:
524 sect_type = lldb::eSectionTypeData;
525 break;
526 case AllocationKind::Bytes:
527 sect_type = lldb::eSectionTypeOther;
528 break;
529 }
530
531 if (!name.empty()) {
532 if (name.equals("__text") || name.equals(".text"))
533 sect_type = lldb::eSectionTypeCode;
534 else if (name.equals("__data") || name.equals(".data"))
535 sect_type = lldb::eSectionTypeCode;
536 else if (name.startswith("__debug_") || name.startswith(".debug_")) {
537 const uint32_t name_idx = name[0] == '_' ? 8 : 7;
538 llvm::StringRef dwarf_name(name.substr(name_idx));
539 switch (dwarf_name[0]) {
540 case 'a':
541 if (dwarf_name.equals("abbrev"))
542 sect_type = lldb::eSectionTypeDWARFDebugAbbrev;
543 else if (dwarf_name.equals("aranges"))
544 sect_type = lldb::eSectionTypeDWARFDebugAranges;
545 else if (dwarf_name.equals("addr"))
546 sect_type = lldb::eSectionTypeDWARFDebugAddr;
547 break;
548
549 case 'f':
550 if (dwarf_name.equals("frame"))
551 sect_type = lldb::eSectionTypeDWARFDebugFrame;
552 break;
553
554 case 'i':
555 if (dwarf_name.equals("info"))
556 sect_type = lldb::eSectionTypeDWARFDebugInfo;
557 break;
558
559 case 'l':
560 if (dwarf_name.equals("line"))
561 sect_type = lldb::eSectionTypeDWARFDebugLine;
562 else if (dwarf_name.equals("loc"))
563 sect_type = lldb::eSectionTypeDWARFDebugLoc;
564 break;
565
566 case 'm':
567 if (dwarf_name.equals("macinfo"))
568 sect_type = lldb::eSectionTypeDWARFDebugMacInfo;
569 break;
570
571 case 'p':
572 if (dwarf_name.equals("pubnames"))
573 sect_type = lldb::eSectionTypeDWARFDebugPubNames;
574 else if (dwarf_name.equals("pubtypes"))
575 sect_type = lldb::eSectionTypeDWARFDebugPubTypes;
576 break;
577
578 case 's':
579 if (dwarf_name.equals("str"))
580 sect_type = lldb::eSectionTypeDWARFDebugStr;
581 else if (dwarf_name.equals("str_offsets"))
582 sect_type = lldb::eSectionTypeDWARFDebugStrOffsets;
583 break;
584
585 case 'r':
586 if (dwarf_name.equals("ranges"))
587 sect_type = lldb::eSectionTypeDWARFDebugRanges;
588 break;
589
590 default:
591 break;
592 }
593 } else if (name.startswith("__apple_") || name.startswith(".apple_")) {
Greg Clayton23f8c952014-03-24 23:10:19 +0000594#if 0
595 const uint32_t name_idx = name[0] == '_' ? 8 : 7;
596 llvm::StringRef apple_name(name.substr(name_idx));
597 switch (apple_name[0])
598 {
599 case 'n':
600 if (apple_name.equals("names"))
601 sect_type = lldb::eSectionTypeDWARFAppleNames;
602 else if (apple_name.equals("namespac") || apple_name.equals("namespaces"))
603 sect_type = lldb::eSectionTypeDWARFAppleNamespaces;
604 break;
605 case 't':
606 if (apple_name.equals("types"))
607 sect_type = lldb::eSectionTypeDWARFAppleTypes;
608 break;
609 case 'o':
610 if (apple_name.equals("objc"))
611 sect_type = lldb::eSectionTypeDWARFAppleObjC;
612 break;
613 default:
614 break;
615 }
616#else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000617 sect_type = lldb::eSectionTypeInvalid;
Greg Clayton23f8c952014-03-24 23:10:19 +0000618#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +0000619 } else if (name.equals("__objc_imageinfo"))
620 sect_type = lldb::eSectionTypeOther;
621 }
622 return sect_type;
Greg Clayton23f8c952014-03-24 23:10:19 +0000623}
624
Kate Stoneb9c1b512016-09-06 20:57:50 +0000625uint8_t *IRExecutionUnit::MemoryManager::allocateCodeSection(
626 uintptr_t Size, unsigned Alignment, unsigned SectionID,
627 llvm::StringRef SectionName) {
628 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000629
Kate Stoneb9c1b512016-09-06 20:57:50 +0000630 uint8_t *return_value = m_default_mm_ap->allocateCodeSection(
631 Size, Alignment, SectionID, SectionName);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000632
Kate Stoneb9c1b512016-09-06 20:57:50 +0000633 m_parent.m_records.push_back(AllocationRecord(
634 (uintptr_t)return_value,
635 lldb::ePermissionsReadable | lldb::ePermissionsExecutable,
636 GetSectionTypeFromSectionName(SectionName, AllocationKind::Code), Size,
637 Alignment, SectionID, SectionName.str().c_str()));
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000638
Kate Stoneb9c1b512016-09-06 20:57:50 +0000639 if (log) {
640 log->Printf("IRExecutionUnit::allocateCodeSection(Size=0x%" PRIx64
641 ", Alignment=%u, SectionID=%u) = %p",
642 (uint64_t)Size, Alignment, SectionID, (void *)return_value);
643 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000644
Kate Stoneb9c1b512016-09-06 20:57:50 +0000645 if (m_parent.m_reported_allocations) {
646 Error err;
647 lldb::ProcessSP process_sp =
648 m_parent.GetBestExecutionContextScope()->CalculateProcess();
649
650 m_parent.CommitOneAllocation(process_sp, err, m_parent.m_records.back());
651 }
652
653 return return_value;
Sean Callanan8dfb68e2013-03-19 00:10:07 +0000654}
655
Kate Stoneb9c1b512016-09-06 20:57:50 +0000656uint8_t *IRExecutionUnit::MemoryManager::allocateDataSection(
657 uintptr_t Size, unsigned Alignment, unsigned SectionID,
658 llvm::StringRef SectionName, bool IsReadOnly) {
659 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan8dfb68e2013-03-19 00:10:07 +0000660
Kate Stoneb9c1b512016-09-06 20:57:50 +0000661 uint8_t *return_value = m_default_mm_ap->allocateDataSection(
662 Size, Alignment, SectionID, SectionName, IsReadOnly);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000663
Kate Stoneb9c1b512016-09-06 20:57:50 +0000664 uint32_t permissions = lldb::ePermissionsReadable;
665 if (!IsReadOnly)
666 permissions |= lldb::ePermissionsWritable;
667 m_parent.m_records.push_back(AllocationRecord(
668 (uintptr_t)return_value, permissions,
669 GetSectionTypeFromSectionName(SectionName, AllocationKind::Data), Size,
670 Alignment, SectionID, SectionName.str().c_str()));
671 if (log) {
672 log->Printf("IRExecutionUnit::allocateDataSection(Size=0x%" PRIx64
673 ", Alignment=%u, SectionID=%u) = %p",
674 (uint64_t)Size, Alignment, SectionID, (void *)return_value);
675 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000676
Kate Stoneb9c1b512016-09-06 20:57:50 +0000677 if (m_parent.m_reported_allocations) {
678 Error err;
679 lldb::ProcessSP process_sp =
680 m_parent.GetBestExecutionContextScope()->CalculateProcess();
681
682 m_parent.CommitOneAllocation(process_sp, err, m_parent.m_records.back());
683 }
684
685 return return_value;
Sean Callanan8dfb68e2013-03-19 00:10:07 +0000686}
687
Sean Callananb2814802016-02-12 21:11:25 +0000688static ConstString
689FindBestAlternateMangledName(const ConstString &demangled,
690 const lldb::LanguageType &lang_type,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000691 const SymbolContext &sym_ctx) {
692 CPlusPlusLanguage::MethodName cpp_name(demangled);
693 std::string scope_qualified_name = cpp_name.GetScopeQualifiedName();
Sean Callananb2814802016-02-12 21:11:25 +0000694
Kate Stoneb9c1b512016-09-06 20:57:50 +0000695 if (!scope_qualified_name.size())
696 return ConstString();
Sean Callananb2814802016-02-12 21:11:25 +0000697
Kate Stoneb9c1b512016-09-06 20:57:50 +0000698 if (!sym_ctx.module_sp)
699 return ConstString();
Sean Callananb2814802016-02-12 21:11:25 +0000700
Kate Stoneb9c1b512016-09-06 20:57:50 +0000701 SymbolVendor *sym_vendor = sym_ctx.module_sp->GetSymbolVendor();
702 if (!sym_vendor)
703 return ConstString();
Sean Callananb2814802016-02-12 21:11:25 +0000704
Kate Stoneb9c1b512016-09-06 20:57:50 +0000705 lldb_private::SymbolFile *sym_file = sym_vendor->GetSymbolFile();
706 if (!sym_file)
707 return ConstString();
Sean Callananb2814802016-02-12 21:11:25 +0000708
Kate Stoneb9c1b512016-09-06 20:57:50 +0000709 std::vector<ConstString> alternates;
710 sym_file->GetMangledNamesForFunction(scope_qualified_name, alternates);
Sean Callananb2814802016-02-12 21:11:25 +0000711
Kate Stoneb9c1b512016-09-06 20:57:50 +0000712 std::vector<ConstString> param_and_qual_matches;
713 std::vector<ConstString> param_matches;
714 for (size_t i = 0; i < alternates.size(); i++) {
715 ConstString alternate_mangled_name = alternates[i];
716 Mangled mangled(alternate_mangled_name, true);
717 ConstString demangled = mangled.GetDemangledName(lang_type);
Sean Callananb2814802016-02-12 21:11:25 +0000718
Kate Stoneb9c1b512016-09-06 20:57:50 +0000719 CPlusPlusLanguage::MethodName alternate_cpp_name(demangled);
720 if (!cpp_name.IsValid())
721 continue;
Sean Callananb2814802016-02-12 21:11:25 +0000722
Kate Stoneb9c1b512016-09-06 20:57:50 +0000723 if (alternate_cpp_name.GetArguments() == cpp_name.GetArguments()) {
724 if (alternate_cpp_name.GetQualifiers() == cpp_name.GetQualifiers())
725 param_and_qual_matches.push_back(alternate_mangled_name);
726 else
727 param_matches.push_back(alternate_mangled_name);
Sean Callananb2814802016-02-12 21:11:25 +0000728 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000729 }
Sean Callananb2814802016-02-12 21:11:25 +0000730
Kate Stoneb9c1b512016-09-06 20:57:50 +0000731 if (param_and_qual_matches.size())
732 return param_and_qual_matches[0]; // It is assumed that there will be only
733 // one!
734 else if (param_matches.size())
735 return param_matches[0]; // Return one of them as a best match
736 else
737 return ConstString();
Sean Callananb2814802016-02-12 21:11:25 +0000738}
739
Kate Stoneb9c1b512016-09-06 20:57:50 +0000740struct IRExecutionUnit::SearchSpec {
741 ConstString name;
742 uint32_t mask;
Sean Callananb2814802016-02-12 21:11:25 +0000743
Kate Stoneb9c1b512016-09-06 20:57:50 +0000744 SearchSpec(ConstString n, uint32_t m = lldb::eFunctionNameTypeFull)
745 : name(n), mask(m) {}
Sean Callananb2814802016-02-12 21:11:25 +0000746};
747
Kate Stoneb9c1b512016-09-06 20:57:50 +0000748void IRExecutionUnit::CollectCandidateCNames(
749 std::vector<IRExecutionUnit::SearchSpec> &C_specs,
750 const ConstString &name) {
751 if (m_strip_underscore && name.AsCString()[0] == '_')
752 C_specs.insert(C_specs.begin(), ConstString(&name.AsCString()[1]));
753 C_specs.push_back(SearchSpec(name));
Sean Callananb2814802016-02-12 21:11:25 +0000754}
755
Kate Stoneb9c1b512016-09-06 20:57:50 +0000756void IRExecutionUnit::CollectCandidateCPlusPlusNames(
757 std::vector<IRExecutionUnit::SearchSpec> &CPP_specs,
758 const std::vector<SearchSpec> &C_specs, const SymbolContext &sc) {
759 for (const SearchSpec &C_spec : C_specs) {
760 const ConstString &name = C_spec.name;
Sean Callananb2814802016-02-12 21:11:25 +0000761
Kate Stoneb9c1b512016-09-06 20:57:50 +0000762 if (CPlusPlusLanguage::IsCPPMangledName(name.GetCString())) {
763 Mangled mangled(name, true);
764 ConstString demangled =
765 mangled.GetDemangledName(lldb::eLanguageTypeC_plus_plus);
Chaoren Lin74a1fc62016-02-24 03:15:21 +0000766
Kate Stoneb9c1b512016-09-06 20:57:50 +0000767 if (demangled) {
768 ConstString best_alternate_mangled_name = FindBestAlternateMangledName(
769 demangled, lldb::eLanguageTypeC_plus_plus, sc);
Chaoren Lin74a1fc62016-02-24 03:15:21 +0000770
Kate Stoneb9c1b512016-09-06 20:57:50 +0000771 if (best_alternate_mangled_name) {
772 CPP_specs.push_back(best_alternate_mangled_name);
Sean Callananb2814802016-02-12 21:11:25 +0000773 }
Chaoren Lin74a1fc62016-02-24 03:15:21 +0000774
Kate Stoneb9c1b512016-09-06 20:57:50 +0000775 CPP_specs.push_back(SearchSpec(demangled, lldb::eFunctionNameTypeFull));
776 }
Sean Callananb2814802016-02-12 21:11:25 +0000777 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000778
779 // Maybe we're looking for a const symbol but the debug info told us it was
780 // const...
781 if (!strncmp(name.GetCString(), "_ZN", 3) &&
782 strncmp(name.GetCString(), "_ZNK", 4)) {
783 std::string fixed_scratch("_ZNK");
784 fixed_scratch.append(name.GetCString() + 3);
785 CPP_specs.push_back(ConstString(fixed_scratch.c_str()));
786 }
787
788 // Maybe we're looking for a static symbol but we thought it was global...
789 if (!strncmp(name.GetCString(), "_Z", 2) &&
790 strncmp(name.GetCString(), "_ZL", 3)) {
791 std::string fixed_scratch("_ZL");
792 fixed_scratch.append(name.GetCString() + 2);
793 CPP_specs.push_back(ConstString(fixed_scratch.c_str()));
794 }
795 }
Sean Callananb2814802016-02-12 21:11:25 +0000796}
797
Kate Stoneb9c1b512016-09-06 20:57:50 +0000798void IRExecutionUnit::CollectFallbackNames(
799 std::vector<SearchSpec> &fallback_specs,
800 const std::vector<SearchSpec> &C_specs) {
801 // As a last-ditch fallback, try the base name for C++ names. It's terrible,
802 // but the DWARF doesn't always encode "extern C" correctly.
803
804 for (const SearchSpec &C_spec : C_specs) {
805 const ConstString &name = C_spec.name;
806
807 if (CPlusPlusLanguage::IsCPPMangledName(name.GetCString())) {
808 Mangled mangled_name(name);
809 ConstString demangled_name =
810 mangled_name.GetDemangledName(lldb::eLanguageTypeC_plus_plus);
811 if (!demangled_name.IsEmpty()) {
812 const char *demangled_cstr = demangled_name.AsCString();
813 const char *lparen_loc = strchr(demangled_cstr, '(');
814 if (lparen_loc) {
815 llvm::StringRef base_name(demangled_cstr,
816 lparen_loc - demangled_cstr);
817 fallback_specs.push_back(ConstString(base_name));
Sean Callanan34ab28a2016-06-02 17:59:47 +0000818 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000819 }
Sean Callanan34ab28a2016-06-02 17:59:47 +0000820 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000821 }
Sean Callanan34ab28a2016-06-02 17:59:47 +0000822}
823
Kate Stoneb9c1b512016-09-06 20:57:50 +0000824lldb::addr_t IRExecutionUnit::FindInSymbols(
825 const std::vector<IRExecutionUnit::SearchSpec> &specs,
826 const lldb_private::SymbolContext &sc) {
827 Target *target = sc.target_sp.get();
Sean Callanan34ab28a2016-06-02 17:59:47 +0000828
Kate Stoneb9c1b512016-09-06 20:57:50 +0000829 if (!target) {
830 // we shouldn't be doing any symbol lookup at all without a target
831 return LLDB_INVALID_ADDRESS;
832 }
Sean Callananfed0e7582016-02-23 23:09:06 +0000833
Kate Stoneb9c1b512016-09-06 20:57:50 +0000834 for (const SearchSpec &spec : specs) {
835 SymbolContextList sc_list;
Sean Callananfed0e7582016-02-23 23:09:06 +0000836
Kate Stoneb9c1b512016-09-06 20:57:50 +0000837 lldb::addr_t best_internal_load_address = LLDB_INVALID_ADDRESS;
Sean Callananfed0e7582016-02-23 23:09:06 +0000838
Kate Stoneb9c1b512016-09-06 20:57:50 +0000839 std::function<bool(lldb::addr_t &, SymbolContextList &,
840 const lldb_private::SymbolContext &)>
841 get_external_load_address = [&best_internal_load_address, target](
842 lldb::addr_t &load_address, SymbolContextList &sc_list,
843 const lldb_private::SymbolContext &sc) -> lldb::addr_t {
844 load_address = LLDB_INVALID_ADDRESS;
Sean Callananfed0e7582016-02-23 23:09:06 +0000845
Kate Stoneb9c1b512016-09-06 20:57:50 +0000846 for (size_t si = 0, se = sc_list.GetSize(); si < se; ++si) {
847 SymbolContext candidate_sc;
848
849 sc_list.GetContextAtIndex(si, candidate_sc);
850
851 const bool is_external =
852 (candidate_sc.function) ||
853 (candidate_sc.symbol && candidate_sc.symbol->IsExternal());
854 if (candidate_sc.symbol) {
855 load_address = candidate_sc.symbol->ResolveCallableAddress(*target);
856
857 if (load_address == LLDB_INVALID_ADDRESS) {
858 if (target->GetProcessSP())
859 load_address =
860 candidate_sc.symbol->GetAddress().GetLoadAddress(target);
861 else
862 load_address = candidate_sc.symbol->GetAddress().GetFileAddress();
863 }
864 }
865
866 if (load_address == LLDB_INVALID_ADDRESS && candidate_sc.function) {
867 if (target->GetProcessSP())
868 load_address = candidate_sc.function->GetAddressRange()
869 .GetBaseAddress()
870 .GetLoadAddress(target);
871 else
872 load_address = candidate_sc.function->GetAddressRange()
873 .GetBaseAddress()
874 .GetFileAddress();
875 }
876
877 if (load_address != LLDB_INVALID_ADDRESS) {
878 if (is_external) {
879 return true;
880 } else if (best_internal_load_address == LLDB_INVALID_ADDRESS) {
881 best_internal_load_address = load_address;
Sean Callananfed0e7582016-02-23 23:09:06 +0000882 load_address = LLDB_INVALID_ADDRESS;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000883 }
884 }
885 }
Sean Callananfed0e7582016-02-23 23:09:06 +0000886
Kate Stoneb9c1b512016-09-06 20:57:50 +0000887 return false;
888 };
Sean Callananfed0e7582016-02-23 23:09:06 +0000889
Kate Stoneb9c1b512016-09-06 20:57:50 +0000890 if (sc.module_sp) {
891 sc.module_sp->FindFunctions(spec.name, NULL, spec.mask,
892 true, // include_symbols
893 false, // include_inlines
894 true, // append
895 sc_list);
896 }
Sean Callananfed0e7582016-02-23 23:09:06 +0000897
Kate Stoneb9c1b512016-09-06 20:57:50 +0000898 lldb::addr_t load_address = LLDB_INVALID_ADDRESS;
Ted Woodwardeee554d2016-03-09 22:05:17 +0000899
Kate Stoneb9c1b512016-09-06 20:57:50 +0000900 if (get_external_load_address(load_address, sc_list, sc)) {
901 return load_address;
902 } else {
903 sc_list.Clear();
904 }
905
906 if (sc_list.GetSize() == 0 && sc.target_sp) {
907 sc.target_sp->GetImages().FindFunctions(spec.name, spec.mask,
908 true, // include_symbols
909 false, // include_inlines
910 true, // append
911 sc_list);
912 }
913
914 if (get_external_load_address(load_address, sc_list, sc)) {
915 return load_address;
916 } else {
917 sc_list.Clear();
918 }
919
920 if (sc_list.GetSize() == 0 && sc.target_sp) {
921 sc.target_sp->GetImages().FindSymbolsWithNameAndType(
922 spec.name, lldb::eSymbolTypeAny, sc_list);
923 }
924
925 if (get_external_load_address(load_address, sc_list, sc)) {
926 return load_address;
927 }
928 // if there are any searches we try after this, add an sc_list.Clear() in an
929 // "else" clause here
930
931 if (best_internal_load_address != LLDB_INVALID_ADDRESS) {
932 return best_internal_load_address;
933 }
934 }
935
936 return LLDB_INVALID_ADDRESS;
937}
938
939lldb::addr_t
940IRExecutionUnit::FindInRuntimes(const std::vector<SearchSpec> &specs,
941 const lldb_private::SymbolContext &sc) {
942 lldb::TargetSP target_sp = sc.target_sp;
943
944 if (!target_sp) {
945 return LLDB_INVALID_ADDRESS;
946 }
947
948 lldb::ProcessSP process_sp = sc.target_sp->GetProcessSP();
949
950 if (!process_sp) {
951 return LLDB_INVALID_ADDRESS;
952 }
953
954 ObjCLanguageRuntime *runtime = process_sp->GetObjCLanguageRuntime();
955
956 if (runtime) {
957 for (const SearchSpec &spec : specs) {
958 lldb::addr_t symbol_load_addr = runtime->LookupRuntimeSymbol(spec.name);
959
960 if (symbol_load_addr != LLDB_INVALID_ADDRESS)
961 return symbol_load_addr;
962 }
963 }
964
965 return LLDB_INVALID_ADDRESS;
966}
967
968lldb::addr_t IRExecutionUnit::FindInUserDefinedSymbols(
969 const std::vector<SearchSpec> &specs,
970 const lldb_private::SymbolContext &sc) {
971 lldb::TargetSP target_sp = sc.target_sp;
972
973 for (const SearchSpec &spec : specs) {
974 lldb::addr_t symbol_load_addr = target_sp->GetPersistentSymbol(spec.name);
975
976 if (symbol_load_addr != LLDB_INVALID_ADDRESS)
977 return symbol_load_addr;
978 }
979
980 return LLDB_INVALID_ADDRESS;
981}
982
983lldb::addr_t
984IRExecutionUnit::FindSymbol(const lldb_private::ConstString &name) {
985 std::vector<SearchSpec> candidate_C_names;
986 std::vector<SearchSpec> candidate_CPlusPlus_names;
987
988 CollectCandidateCNames(candidate_C_names, name);
989
990 lldb::addr_t ret = FindInSymbols(candidate_C_names, m_sym_ctx);
991 if (ret == LLDB_INVALID_ADDRESS)
992 ret = FindInRuntimes(candidate_C_names, m_sym_ctx);
993
994 if (ret == LLDB_INVALID_ADDRESS)
995 ret = FindInUserDefinedSymbols(candidate_C_names, m_sym_ctx);
996
997 if (ret == LLDB_INVALID_ADDRESS) {
998 CollectCandidateCPlusPlusNames(candidate_CPlusPlus_names, candidate_C_names,
999 m_sym_ctx);
1000 ret = FindInSymbols(candidate_CPlusPlus_names, m_sym_ctx);
1001 }
1002
1003 if (ret == LLDB_INVALID_ADDRESS) {
1004 std::vector<SearchSpec> candidate_fallback_names;
1005
1006 CollectFallbackNames(candidate_fallback_names, candidate_C_names);
1007 ret = FindInSymbols(candidate_fallback_names, m_sym_ctx);
1008 }
1009
1010 return ret;
1011}
1012
1013void IRExecutionUnit::GetStaticInitializers(
1014 std::vector<lldb::addr_t> &static_initializers) {
1015 if (llvm::GlobalVariable *global_ctors =
1016 m_module->getNamedGlobal("llvm.global_ctors")) {
1017 if (llvm::ConstantArray *ctor_array = llvm::dyn_cast<llvm::ConstantArray>(
1018 global_ctors->getInitializer())) {
1019 for (llvm::Use &ctor_use : ctor_array->operands()) {
1020 if (llvm::ConstantStruct *ctor_struct =
1021 llvm::dyn_cast<llvm::ConstantStruct>(ctor_use)) {
1022 lldbassert(ctor_struct->getNumOperands() ==
1023 3); // this is standardized
1024 if (llvm::Function *ctor_function =
1025 llvm::dyn_cast<llvm::Function>(ctor_struct->getOperand(1))) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001026 ConstString ctor_function_name_cs(ctor_function->getName().str());
1027
1028 for (JittedFunction &jitted_function : m_jitted_functions) {
1029 if (ctor_function_name_cs == jitted_function.m_name) {
1030 if (jitted_function.m_remote_addr != LLDB_INVALID_ADDRESS) {
1031 static_initializers.push_back(jitted_function.m_remote_addr);
Ted Woodwardeee554d2016-03-09 22:05:17 +00001032 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001033 break;
1034 }
Sean Callananfed0e7582016-02-23 23:09:06 +00001035 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001036 }
Sean Callananb2814802016-02-12 21:11:25 +00001037 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001038 }
Sean Callananb2814802016-02-12 21:11:25 +00001039 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001040 }
Sean Callananbd4dc692016-03-21 22:23:38 +00001041}
1042
Jim Ingham27e5fe82015-01-27 18:03:05 +00001043uint64_t
Kate Stoneb9c1b512016-09-06 20:57:50 +00001044IRExecutionUnit::MemoryManager::getSymbolAddress(const std::string &Name) {
1045 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
Greg Claytond6171a72015-07-02 16:43:49 +00001046
Kate Stoneb9c1b512016-09-06 20:57:50 +00001047 ConstString name_cs(Name.c_str());
Chaoren Lin74a1fc62016-02-24 03:15:21 +00001048
Kate Stoneb9c1b512016-09-06 20:57:50 +00001049 lldb::addr_t ret = m_parent.FindSymbol(name_cs);
Chaoren Lin74a1fc62016-02-24 03:15:21 +00001050
Kate Stoneb9c1b512016-09-06 20:57:50 +00001051 if (ret == LLDB_INVALID_ADDRESS) {
1052 if (log)
1053 log->Printf(
1054 "IRExecutionUnit::getSymbolAddress(Name=\"%s\") = <not found>",
1055 Name.c_str());
Sean Callananb2814802016-02-12 21:11:25 +00001056
Kate Stoneb9c1b512016-09-06 20:57:50 +00001057 m_parent.ReportSymbolLookupError(name_cs);
1058 return 0xbad0bad0;
1059 } else {
1060 if (log)
1061 log->Printf("IRExecutionUnit::getSymbolAddress(Name=\"%s\") = %" PRIx64,
1062 Name.c_str(), ret);
1063 return ret;
1064 }
Jim Ingham27e5fe82015-01-27 18:03:05 +00001065}
1066
Kate Stoneb9c1b512016-09-06 20:57:50 +00001067void *IRExecutionUnit::MemoryManager::getPointerToNamedFunction(
1068 const std::string &Name, bool AbortOnFailure) {
1069 assert(sizeof(void *) == 8);
Chaoren Lin74a1fc62016-02-24 03:15:21 +00001070
Kate Stoneb9c1b512016-09-06 20:57:50 +00001071 return (void *)getSymbolAddress(Name);
Jim Ingham27e5fe82015-01-27 18:03:05 +00001072}
1073
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001074lldb::addr_t
Kate Stoneb9c1b512016-09-06 20:57:50 +00001075IRExecutionUnit::GetRemoteAddressForLocal(lldb::addr_t local_address) {
1076 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
Sean Callananffae9442013-06-27 01:42:47 +00001077
Kate Stoneb9c1b512016-09-06 20:57:50 +00001078 for (AllocationRecord &record : m_records) {
1079 if (local_address >= record.m_host_address &&
1080 local_address < record.m_host_address + record.m_size) {
1081 if (record.m_process_address == LLDB_INVALID_ADDRESS)
1082 return LLDB_INVALID_ADDRESS;
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +00001083
Kate Stoneb9c1b512016-09-06 20:57:50 +00001084 lldb::addr_t ret =
1085 record.m_process_address + (local_address - record.m_host_address);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +00001086
Kate Stoneb9c1b512016-09-06 20:57:50 +00001087 if (log) {
1088 log->Printf(
1089 "IRExecutionUnit::GetRemoteAddressForLocal() found 0x%" PRIx64
1090 " in [0x%" PRIx64 "..0x%" PRIx64 "], and returned 0x%" PRIx64
1091 " from [0x%" PRIx64 "..0x%" PRIx64 "].",
1092 local_address, (uint64_t)record.m_host_address,
1093 (uint64_t)record.m_host_address + (uint64_t)record.m_size, ret,
1094 record.m_process_address, record.m_process_address + record.m_size);
1095 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +00001096
Kate Stoneb9c1b512016-09-06 20:57:50 +00001097 return ret;
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001098 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001099 }
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001100
Kate Stoneb9c1b512016-09-06 20:57:50 +00001101 return LLDB_INVALID_ADDRESS;
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001102}
1103
1104IRExecutionUnit::AddrRange
Kate Stoneb9c1b512016-09-06 20:57:50 +00001105IRExecutionUnit::GetRemoteRangeForLocal(lldb::addr_t local_address) {
1106 for (AllocationRecord &record : m_records) {
1107 if (local_address >= record.m_host_address &&
1108 local_address < record.m_host_address + record.m_size) {
1109 if (record.m_process_address == LLDB_INVALID_ADDRESS)
1110 return AddrRange(0, 0);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +00001111
Kate Stoneb9c1b512016-09-06 20:57:50 +00001112 return AddrRange(record.m_process_address, record.m_size);
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001113 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001114 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +00001115
Kate Stoneb9c1b512016-09-06 20:57:50 +00001116 return AddrRange(0, 0);
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001117}
1118
Kate Stoneb9c1b512016-09-06 20:57:50 +00001119bool IRExecutionUnit::CommitOneAllocation(lldb::ProcessSP &process_sp,
1120 Error &error,
1121 AllocationRecord &record) {
1122 if (record.m_process_address != LLDB_INVALID_ADDRESS) {
1123 return true;
1124 }
1125
1126 switch (record.m_sect_type) {
1127 case lldb::eSectionTypeInvalid:
1128 case lldb::eSectionTypeDWARFDebugAbbrev:
1129 case lldb::eSectionTypeDWARFDebugAddr:
1130 case lldb::eSectionTypeDWARFDebugAranges:
1131 case lldb::eSectionTypeDWARFDebugFrame:
1132 case lldb::eSectionTypeDWARFDebugInfo:
1133 case lldb::eSectionTypeDWARFDebugLine:
1134 case lldb::eSectionTypeDWARFDebugLoc:
1135 case lldb::eSectionTypeDWARFDebugMacInfo:
1136 case lldb::eSectionTypeDWARFDebugPubNames:
1137 case lldb::eSectionTypeDWARFDebugPubTypes:
1138 case lldb::eSectionTypeDWARFDebugRanges:
1139 case lldb::eSectionTypeDWARFDebugStr:
1140 case lldb::eSectionTypeDWARFDebugStrOffsets:
1141 case lldb::eSectionTypeDWARFAppleNames:
1142 case lldb::eSectionTypeDWARFAppleTypes:
1143 case lldb::eSectionTypeDWARFAppleNamespaces:
1144 case lldb::eSectionTypeDWARFAppleObjC:
1145 error.Clear();
1146 break;
1147 default:
1148 const bool zero_memory = false;
1149 record.m_process_address =
1150 Malloc(record.m_size, record.m_alignment, record.m_permissions,
1151 eAllocationPolicyProcessOnly, zero_memory, error);
1152 break;
1153 }
1154
1155 return error.Success();
1156}
1157
1158bool IRExecutionUnit::CommitAllocations(lldb::ProcessSP &process_sp) {
1159 bool ret = true;
1160
1161 lldb_private::Error err;
1162
1163 for (AllocationRecord &record : m_records) {
1164 ret = CommitOneAllocation(process_sp, err, record);
1165
1166 if (!ret) {
1167 break;
Sean Callananbd4dc692016-03-21 22:23:38 +00001168 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001169 }
1170
1171 if (!ret) {
1172 for (AllocationRecord &record : m_records) {
1173 if (record.m_process_address != LLDB_INVALID_ADDRESS) {
1174 Free(record.m_process_address, err);
1175 record.m_process_address = LLDB_INVALID_ADDRESS;
1176 }
Sean Callananbd4dc692016-03-21 22:23:38 +00001177 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001178 }
1179
1180 return ret;
Sean Callananbd4dc692016-03-21 22:23:38 +00001181}
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +00001182
Kate Stoneb9c1b512016-09-06 20:57:50 +00001183void IRExecutionUnit::ReportAllocations(llvm::ExecutionEngine &engine) {
1184 m_reported_allocations = true;
Sean Callananbd4dc692016-03-21 22:23:38 +00001185
Kate Stoneb9c1b512016-09-06 20:57:50 +00001186 for (AllocationRecord &record : m_records) {
1187 if (record.m_process_address == LLDB_INVALID_ADDRESS)
1188 continue;
Sean Callananbd4dc692016-03-21 22:23:38 +00001189
Kate Stoneb9c1b512016-09-06 20:57:50 +00001190 if (record.m_section_id == eSectionIDInvalid)
1191 continue;
1192
1193 engine.mapSectionAddress((void *)record.m_host_address,
1194 record.m_process_address);
1195 }
1196
1197 // Trigger re-application of relocations.
1198 engine.finalizeObject();
1199}
1200
1201bool IRExecutionUnit::WriteData(lldb::ProcessSP &process_sp) {
1202 bool wrote_something = false;
1203 for (AllocationRecord &record : m_records) {
1204 if (record.m_process_address != LLDB_INVALID_ADDRESS) {
1205 lldb_private::Error err;
1206 WriteMemory(record.m_process_address, (uint8_t *)record.m_host_address,
1207 record.m_size, err);
1208 if (err.Success())
1209 wrote_something = true;
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001210 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001211 }
1212 return wrote_something;
1213}
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +00001214
Kate Stoneb9c1b512016-09-06 20:57:50 +00001215void IRExecutionUnit::AllocationRecord::dump(Log *log) {
1216 if (!log)
1217 return;
1218
1219 log->Printf("[0x%llx+0x%llx]->0x%llx (alignment %d, section ID %d, name %s)",
1220 (unsigned long long)m_host_address, (unsigned long long)m_size,
1221 (unsigned long long)m_process_address, (unsigned)m_alignment,
1222 (unsigned)m_section_id, m_name.c_str());
1223}
1224
1225lldb::ByteOrder IRExecutionUnit::GetByteOrder() const {
1226 ExecutionContext exe_ctx(GetBestExecutionContextScope());
1227 return exe_ctx.GetByteOrder();
1228}
1229
1230uint32_t IRExecutionUnit::GetAddressByteSize() const {
1231 ExecutionContext exe_ctx(GetBestExecutionContextScope());
1232 return exe_ctx.GetAddressByteSize();
1233}
1234
1235void IRExecutionUnit::PopulateSymtab(lldb_private::ObjectFile *obj_file,
1236 lldb_private::Symtab &symtab) {
1237 // No symbols yet...
1238}
1239
1240void IRExecutionUnit::PopulateSectionList(
1241 lldb_private::ObjectFile *obj_file,
1242 lldb_private::SectionList &section_list) {
1243 for (AllocationRecord &record : m_records) {
1244 if (record.m_size > 0) {
1245 lldb::SectionSP section_sp(new lldb_private::Section(
1246 obj_file->GetModule(), obj_file, record.m_section_id,
1247 ConstString(record.m_name), record.m_sect_type,
1248 record.m_process_address, record.m_size,
1249 record.m_host_address, // file_offset (which is the host address for
1250 // the data)
1251 record.m_size, // file_size
1252 0,
1253 record.m_permissions)); // flags
1254 section_list.AddSection(section_sp);
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001255 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001256 }
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001257}
1258
Kate Stoneb9c1b512016-09-06 20:57:50 +00001259bool IRExecutionUnit::GetArchitecture(lldb_private::ArchSpec &arch) {
1260 ExecutionContext exe_ctx(GetBestExecutionContextScope());
1261 Target *target = exe_ctx.GetTargetPtr();
1262 if (target)
1263 arch = target->GetArchitecture();
1264 else
1265 arch.Clear();
1266 return arch.IsValid();
1267}
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +00001268
Kate Stoneb9c1b512016-09-06 20:57:50 +00001269lldb::ModuleSP IRExecutionUnit::GetJITModule() {
1270 ExecutionContext exe_ctx(GetBestExecutionContextScope());
1271 Target *target = exe_ctx.GetTargetPtr();
1272 if (target) {
1273 lldb::ModuleSP jit_module_sp = lldb_private::Module::CreateJITModule(
1274 std::static_pointer_cast<lldb_private::ObjectFileJITDelegate>(
1275 shared_from_this()));
1276 if (jit_module_sp) {
1277 bool changed = false;
1278 jit_module_sp->SetLoadAddress(*target, 0, true, changed);
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001279 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001280 return jit_module_sp;
1281 }
1282 return lldb::ModuleSP();
Greg Clayton23f8c952014-03-24 23:10:19 +00001283}