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