LLDB mainline
IRExecutionUnit.cpp
Go to the documentation of this file.
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/DiagnosticHandler.h"
13#include "llvm/IR/DiagnosticInfo.h"
14#include "llvm/IR/LLVMContext.h"
15#include "llvm/IR/Module.h"
16#include "llvm/Support/Error.h"
17#include "llvm/Support/SourceMgr.h"
18#include "llvm/Support/raw_ostream.h"
19
20#include "lldb/Core/Debugger.h"
22#include "lldb/Core/Module.h"
23#include "lldb/Core/Section.h"
26#include "lldb/Host/HostInfo.h"
31#include "lldb/Target/Target.h"
36#include "lldb/Utility/Log.h"
37#include "lldb/lldb-defines.h"
38
39using namespace lldb_private;
40
41IRExecutionUnit::IRExecutionUnit(std::unique_ptr<llvm::LLVMContext> &context_up,
42 std::unique_ptr<llvm::Module> &module_up,
43 ConstString &name,
44 const lldb::TargetSP &target_sp,
45 const SymbolContext &sym_ctx,
46 std::vector<std::string> &cpu_features)
47 : IRMemoryMap(target_sp), m_context_up(std::move(context_up)),
48 m_module_up(std::move(module_up)), m_module(m_module_up.get()),
49 m_cpu_features(cpu_features), m_name(name),
51 sym_ctx, m_module_up
52 ? m_module_up->getDataLayout().getGlobalPrefix() == '_'
53 : false),
57
59 lldb::ProcessSP &process_wp) {
61
62 ExecutionContext exe_ctx(process_wp);
63
64 Status ret;
65
66 ret.Clear();
67
68 lldb::addr_t func_local_addr = LLDB_INVALID_ADDRESS;
69 lldb::addr_t func_remote_addr = LLDB_INVALID_ADDRESS;
70
71 for (JittedFunction &function : m_jitted_functions) {
72 if (function.m_name == m_name) {
73 func_local_addr = function.m_local_addr;
74 func_remote_addr = function.m_remote_addr;
75 }
76 }
77
78 if (func_local_addr == LLDB_INVALID_ADDRESS) {
80 "Couldn't find function {0} for disassembly", m_name);
81 return ret;
82 }
83
84 LLDB_LOGF(log,
85 "Found function, has local address 0x%" PRIx64
86 " and remote address 0x%" PRIx64,
87 (uint64_t)func_local_addr, (uint64_t)func_remote_addr);
88
89 std::pair<lldb::addr_t, lldb::addr_t> func_range;
90
91 func_range = GetRemoteRangeForLocal(func_local_addr);
92
93 if (func_range.first == 0 && func_range.second == 0) {
95 "Couldn't find code range for function {0}", m_name);
96 return ret;
97 }
98
99 LLDB_LOGF(log, "Function's code range is [0x%" PRIx64 "+0x%" PRIx64 "]",
100 func_range.first, func_range.second);
101
102 Target *target = exe_ctx.GetTargetPtr();
103 if (!target) {
104 ret = Status::FromErrorString("Couldn't find the target");
105 return ret;
106 }
107
109 new DataBufferHeap(func_range.second, 0));
110
111 Process *process = exe_ctx.GetProcessPtr();
112 Status err;
113 process->ReadMemory(func_remote_addr, buffer_sp->GetBytes(),
114 buffer_sp->GetByteSize(), err);
115
116 if (!err.Success()) {
117 ret = Status::FromErrorStringWithFormat("Couldn't read from process: %s",
118 err.AsCString("unknown error"));
119 return ret;
120 }
121
122 ArchSpec arch(target->GetArchitecture());
123
124 const char *plugin_name = nullptr;
125 const char *flavor_string = nullptr;
126 const char *cpu_string = nullptr;
127 const char *features_string = nullptr;
129 arch, flavor_string, cpu_string, features_string, plugin_name);
130
131 if (!disassembler_sp) {
133 "Unable to find disassembler plug-in for %s architecture.",
134 arch.GetArchitectureName());
135 return ret;
136 }
137
138 if (!process) {
139 ret = Status::FromErrorString("Couldn't find the process");
140 return ret;
141 }
142
143 DataExtractor extractor(buffer_sp, process->GetByteOrder(),
145
146 if (log) {
147 LLDB_LOGF(log, "Function data has contents:");
148 extractor.PutToLog(log, 0, extractor.GetByteSize(), func_remote_addr, 16,
150 }
151
152 disassembler_sp->DecodeInstructions(Address(func_remote_addr), extractor, 0,
153 UINT32_MAX, false, false);
154
155 InstructionList &instruction_list = disassembler_sp->GetInstructionList();
156 instruction_list.Dump(&stream, true, true, /*show_control_flow_kind=*/false,
157 &exe_ctx);
158
159 return ret;
160}
161
162namespace {
163struct IRExecDiagnosticHandler : public llvm::DiagnosticHandler {
164 Status *err;
165 IRExecDiagnosticHandler(Status *err) : err(err) {}
166 bool handleDiagnostics(const llvm::DiagnosticInfo &DI) override {
167 if (DI.getSeverity() == llvm::DS_Error) {
168 const auto &DISM = llvm::cast<llvm::DiagnosticInfoSrcMgr>(DI);
169 if (err && err->Success()) {
171 "IRExecution error: %s",
172 DISM.getSMDiag().getMessage().str().c_str());
173 }
174 }
175
176 return true;
177 }
178};
179} // namespace
180
184
186 lldb::addr_t &func_end) {
187 lldb::ProcessSP process_sp(GetProcessWP().lock());
188
189 static std::recursive_mutex s_runnable_info_mutex;
190
191 func_addr = LLDB_INVALID_ADDRESS;
192 func_end = LLDB_INVALID_ADDRESS;
193
194 if (!process_sp) {
195 error =
196 Status::FromErrorString("Couldn't write the JIT compiled code into the "
197 "process because the process is invalid");
198 return;
199 }
200
201 if (m_did_jit) {
202 func_addr = m_function_load_addr;
203 func_end = m_function_end_load_addr;
204
205 return;
206 };
207
208 std::lock_guard<std::recursive_mutex> guard(s_runnable_info_mutex);
209
210 m_did_jit = true;
211
213
214 std::string error_string;
215
216 if (log) {
217 std::string s;
218 llvm::raw_string_ostream oss(s);
219
220 m_module->print(oss, nullptr);
221
222 LLDB_LOGF(log, "Module being sent to JIT: \n%s", s.c_str());
223 }
224
225 m_module_up->getContext().setDiagnosticHandler(
226 std::make_unique<IRExecDiagnosticHandler>(&error));
227
228 llvm::EngineBuilder builder(std::move(m_module_up));
229 llvm::Triple triple(m_module->getTargetTriple());
230
231 builder.setEngineKind(llvm::EngineKind::JIT)
232 .setErrorStr(&error_string)
233 .setRelocationModel(triple.isOSBinFormatMachO() ? llvm::Reloc::PIC_
234 : llvm::Reloc::Static)
235 .setMCJITMemoryManager(std::make_unique<MemoryManager>(*this))
236 .setOptLevel(llvm::CodeGenOptLevel::Less);
237
238 // Resulted jitted code can be placed too far from the code in the binary
239 // and thus can contain more than +-2GB jumps, that are not available
240 // in RISC-V without large code model.
241 if (triple.isRISCV64())
242 builder.setCodeModel(llvm::CodeModel::Large);
243
244 llvm::StringRef mArch;
245 llvm::StringRef mCPU;
246 llvm::SmallVector<std::string, 0> mAttrs;
247
248 for (std::string &feature : m_cpu_features)
249 mAttrs.push_back(feature);
250
251 llvm::TargetMachine *target_machine =
252 builder.selectTarget(triple, mArch, mCPU, mAttrs);
253
254 m_execution_engine_up.reset(builder.create(target_machine));
255
257 error = Status::FromErrorStringWithFormat("Couldn't JIT the function: %s",
258 error_string.c_str());
259 return;
260 }
261
262 class ObjectDumper : public llvm::ObjectCache {
263 public:
264 ObjectDumper(FileSpec output_dir) : m_out_dir(output_dir) {}
265 void notifyObjectCompiled(const llvm::Module *module,
266 llvm::MemoryBufferRef object) override {
267 int fd = 0;
268 llvm::SmallVector<char, 256> result_path;
269 std::string object_name_model =
270 "jit-object-" + module->getModuleIdentifier() + "-%%%.o";
271 FileSpec model_spec
272 = m_out_dir.CopyByAppendingPathComponent(object_name_model);
273 std::string model_path = model_spec.GetPath();
274
275 std::error_code result
276 = llvm::sys::fs::createUniqueFile(model_path, fd, result_path);
277 if (!result) {
278 llvm::raw_fd_ostream fds(fd, true);
279 fds.write(object.getBufferStart(), object.getBufferSize());
280 }
281 }
282 std::unique_ptr<llvm::MemoryBuffer>
283 getObject(const llvm::Module *module) override {
284 // Return nothing - we're just abusing the object-cache mechanism to dump
285 // objects.
286 return nullptr;
287 }
288 private:
289 FileSpec m_out_dir;
290 };
291
292 FileSpec save_objects_dir = process_sp->GetTarget().GetSaveJITObjectsDir();
293 if (save_objects_dir) {
294 m_object_cache_up = std::make_unique<ObjectDumper>(save_objects_dir);
295 m_execution_engine_up->setObjectCache(m_object_cache_up.get());
296 }
297
298 // Make sure we see all sections, including ones that don't have
299 // relocations...
300 m_execution_engine_up->setProcessAllSections(true);
301
302 m_execution_engine_up->DisableLazyCompilation();
303
304 for (llvm::Function &function : *m_module) {
305 if (function.isDeclaration() || function.hasPrivateLinkage())
306 continue;
307
308 const bool external = !function.hasLocalLinkage();
309
310 void *fun_ptr = m_execution_engine_up->getPointerToFunction(&function);
311
312 if (!error.Success()) {
313 // We got an error through our callback!
314 return;
315 }
316
317 if (!fun_ptr) {
319 "'%s' was in the JITted module but wasn't lowered",
320 function.getName().str().c_str());
321 return;
322 }
324 function.getName().str().c_str(), external, reinterpret_cast<uintptr_t>(fun_ptr)));
325 }
326
327 CommitAllocations(process_sp);
329
330 // We have to do this after calling ReportAllocations because for the MCJIT,
331 // getGlobalValueAddress will cause the JIT to perform all relocations. That
332 // can only be done once, and has to happen after we do the remapping from
333 // local -> remote. That means we don't know the local address of the
334 // Variables, but we don't need that for anything, so that's okay.
335
336 std::function<void(llvm::GlobalValue &)> RegisterOneValue = [this](
337 llvm::GlobalValue &val) {
338 if (val.hasExternalLinkage() && !val.isDeclaration()) {
339 uint64_t var_ptr_addr =
340 m_execution_engine_up->getGlobalValueAddress(val.getName().str());
341
342 lldb::addr_t remote_addr = GetRemoteAddressForLocal(var_ptr_addr);
343
344 // This is a really unfortunae API that sometimes returns local addresses
345 // and sometimes returns remote addresses, based on whether the variable
346 // was relocated during ReportAllocations or not.
347
348 if (remote_addr == LLDB_INVALID_ADDRESS) {
349 remote_addr = var_ptr_addr;
350 }
351
352 if (var_ptr_addr != 0)
354 val.getName().str().c_str(), LLDB_INVALID_ADDRESS, remote_addr));
355 }
356 };
357
358 for (llvm::GlobalVariable &global_var : m_module->globals()) {
359 RegisterOneValue(global_var);
360 }
361
362 for (llvm::GlobalAlias &global_alias : m_module->aliases()) {
363 RegisterOneValue(global_alias);
364 }
365
366 WriteData(process_sp);
367
368 if (m_failed_lookups.size()) {
369 StreamString ss;
370
371 ss.PutCString("Couldn't look up symbols:\n");
372
373 bool emitNewLine = false;
374
375 for (ConstString failed_lookup : m_failed_lookups) {
376 if (emitNewLine)
377 ss.PutCString("\n");
378 emitNewLine = true;
379 ss.PutCString(" ");
380 ss.PutCString(Mangled(failed_lookup).GetDemangledName().GetStringRef());
381 }
382
383 m_failed_lookups.clear();
384 ss.PutCString(
385 "\nHint: The expression tried to call a function that is not present "
386 "in the target, perhaps because it was optimized out by the compiler.");
387 error = Status(ss.GetString().str());
388
389 return;
390 }
391
394
395 for (JittedFunction &jitted_function : m_jitted_functions) {
396 jitted_function.m_remote_addr =
397 GetRemoteAddressForLocal(jitted_function.m_local_addr);
398
399 if (!m_name.IsEmpty() && jitted_function.m_name == m_name) {
400 AddrRange func_range =
401 GetRemoteRangeForLocal(jitted_function.m_local_addr);
402 m_function_end_load_addr = func_range.first + func_range.second;
403 m_function_load_addr = jitted_function.m_remote_addr;
404 }
405 }
406
407 if (log) {
408 LLDB_LOGF(log, "Code can be run in the target.");
409
410 StreamString disassembly_stream;
411
412 Status err = DisassembleFunction(disassembly_stream, process_sp);
413
414 if (!err.Success()) {
415 LLDB_LOGF(log, "Couldn't disassemble function : %s",
416 err.AsCString("unknown error"));
417 } else {
418 LLDB_LOGF(log, "Function disassembly:\n%s", disassembly_stream.GetData());
419 }
420
421 LLDB_LOGF(log, "Sections: ");
422 for (AllocationRecord &record : m_records) {
423 if (record.m_process_address != LLDB_INVALID_ADDRESS) {
424 record.dump(log);
425
426 DataBufferHeap my_buffer(record.m_size, 0);
427 Status err;
428 ReadMemory(my_buffer.GetBytes(), record.m_process_address,
429 record.m_size, err);
430
431 if (err.Success()) {
432 DataExtractor my_extractor(my_buffer.GetBytes(),
433 my_buffer.GetByteSize(),
435 my_extractor.PutToLog(log, 0, my_buffer.GetByteSize(),
436 record.m_process_address, 16,
438 }
439 } else {
440 record.dump(log);
441
442 DataExtractor my_extractor((const void *)record.m_host_address,
443 record.m_size, lldb::eByteOrderBig, 8);
444 my_extractor.PutToLog(log, 0, record.m_size, record.m_host_address, 16,
446 }
447 }
448 }
449
450 func_addr = m_function_load_addr;
451 func_end = m_function_end_load_addr;
452}
453
459
461 : m_default_mm_up(new llvm::SectionMemoryManager()), m_parent(parent) {}
462
464
466 const llvm::StringRef &name, IRExecutionUnit::AllocationKind alloc_kind) {
468 switch (alloc_kind) {
470 sect_type = lldb::eSectionTypeCode;
471 break;
473 sect_type = lldb::eSectionTypeCode;
474 break;
476 sect_type = lldb::eSectionTypeData;
477 break;
479 sect_type = lldb::eSectionTypeData;
480 break;
482 sect_type = lldb::eSectionTypeOther;
483 break;
484 }
485
486 if (!name.empty()) {
487 if (name == "__text" || name == ".text")
488 sect_type = lldb::eSectionTypeCode;
489 else if (name == "__data" || name == ".data")
490 sect_type = lldb::eSectionTypeCode;
491 else if (name.starts_with("__debug_") || name.starts_with(".debug_")) {
492 const uint32_t name_idx = name[0] == '_' ? 8 : 7;
493 llvm::StringRef dwarf_name(name.substr(name_idx));
494 sect_type = ObjectFile::GetDWARFSectionTypeFromName(dwarf_name);
495 } else if (name.starts_with("__apple_") || name.starts_with(".apple_"))
496 sect_type = lldb::eSectionTypeInvalid;
497 else if (name == "__objc_imageinfo")
498 sect_type = lldb::eSectionTypeOther;
499 }
500 return sect_type;
501}
502
504 uintptr_t Size, unsigned Alignment, unsigned SectionID,
505 llvm::StringRef SectionName) {
507
508 uint8_t *return_value = m_default_mm_up->allocateCodeSection(
509 Size, Alignment, SectionID, SectionName);
510
511 m_parent.m_records.push_back(AllocationRecord(
512 (uintptr_t)return_value,
513 lldb::ePermissionsReadable | lldb::ePermissionsExecutable,
515 Alignment, SectionID, SectionName.str().c_str()));
516
517 LLDB_LOGF(log,
518 "IRExecutionUnit::allocateCodeSection(Size=0x%" PRIx64
519 ", Alignment=%u, SectionID=%u) = %p",
520 (uint64_t)Size, Alignment, SectionID, (void *)return_value);
521
522 if (m_parent.m_reported_allocations) {
523 Status err;
524 lldb::ProcessSP process_sp =
525 m_parent.GetBestExecutionContextScope()->CalculateProcess();
526
527 m_parent.CommitOneAllocation(process_sp, err, m_parent.m_records.back());
528 }
529
530 return return_value;
531}
532
534 uintptr_t Size, unsigned Alignment, unsigned SectionID,
535 llvm::StringRef SectionName, bool IsReadOnly) {
537
538 uint8_t *return_value = m_default_mm_up->allocateDataSection(
539 Size, Alignment, SectionID, SectionName, IsReadOnly);
540
541 uint32_t permissions = lldb::ePermissionsReadable;
542 if (!IsReadOnly)
543 permissions |= lldb::ePermissionsWritable;
544 m_parent.m_records.push_back(AllocationRecord(
545 (uintptr_t)return_value, permissions,
547 Alignment, SectionID, SectionName.str().c_str()));
548 LLDB_LOGF(log,
549 "IRExecutionUnit::allocateDataSection(Size=0x%" PRIx64
550 ", Alignment=%u, SectionID=%u) = %p",
551 (uint64_t)Size, Alignment, SectionID, (void *)return_value);
552
553 if (m_parent.m_reported_allocations) {
554 Status err;
555 lldb::ProcessSP process_sp =
556 m_parent.GetBestExecutionContextScope()->CalculateProcess();
557
558 m_parent.CommitOneAllocation(process_sp, err, m_parent.m_records.back());
559 }
560
561 return return_value;
562}
563
565 std::vector<lldb::addr_t> &static_initializers) {
567
568 llvm::GlobalVariable *global_ctors =
569 m_module->getNamedGlobal("llvm.global_ctors");
570 if (!global_ctors) {
571 LLDB_LOG(log, "Couldn't find llvm.global_ctors.");
572 return;
573 }
574 auto *ctor_array =
575 llvm::dyn_cast<llvm::ConstantArray>(global_ctors->getInitializer());
576 if (!ctor_array) {
577 LLDB_LOG(log, "llvm.global_ctors not a ConstantArray.");
578 return;
579 }
580
581 for (llvm::Use &ctor_use : ctor_array->operands()) {
582 auto *ctor_struct = llvm::dyn_cast<llvm::ConstantStruct>(ctor_use);
583 if (!ctor_struct)
584 continue;
585 // this is standardized
586 lldbassert(ctor_struct->getNumOperands() == 3);
587 auto *ctor_function =
588 llvm::dyn_cast<llvm::Function>(ctor_struct->getOperand(1));
589 if (!ctor_function) {
590 LLDB_LOG(log, "global_ctor doesn't contain an llvm::Function");
591 continue;
592 }
593
594 ConstString ctor_function_name(ctor_function->getName().str());
595 LLDB_LOG(log, "Looking for callable jitted function with name {0}.",
596 ctor_function_name);
597
598 for (JittedFunction &jitted_function : m_jitted_functions) {
599 if (ctor_function_name != jitted_function.m_name)
600 continue;
601 if (jitted_function.m_remote_addr == LLDB_INVALID_ADDRESS) {
602 LLDB_LOG(log, "Found jitted function with invalid address.");
603 continue;
604 }
605 static_initializers.push_back(jitted_function.m_remote_addr);
606 LLDB_LOG(log, "Calling function at address {0:x}.",
607 jitted_function.m_remote_addr);
608 break;
609 }
610 }
611}
612
613llvm::JITSymbol
615 bool missing_weak = false;
616 uint64_t addr = GetSymbolAddressAndPresence(Name, missing_weak);
617 // This is a weak symbol:
618 if (missing_weak)
619 return llvm::JITSymbol(addr,
620 llvm::JITSymbolFlags::Exported | llvm::JITSymbolFlags::Weak);
621 else
622 return llvm::JITSymbol(addr, llvm::JITSymbolFlags::Exported);
623}
624
625uint64_t
627 bool missing_weak = false;
628 return GetSymbolAddressAndPresence(Name, missing_weak);
629}
630
631uint64_t
633 const std::string &Name, bool &missing_weak) {
635
636 ConstString name_cs(Name);
637
638 lldb::addr_t ret = m_parent.FindSymbol(name_cs, missing_weak);
639
640 if (ret == LLDB_INVALID_ADDRESS) {
641 LLDB_LOGF(log,
642 "IRExecutionUnit::getSymbolAddress(Name=\"%s\") = <not found>",
643 Name.c_str());
644
645 m_parent.ReportSymbolLookupError(name_cs);
646 return 0;
647 } else {
648 LLDB_LOGF(log, "IRExecutionUnit::getSymbolAddress(Name=\"%s\") = %" PRIx64,
649 Name.c_str(), ret);
650 return ret;
651 }
652}
653
655 const std::string &Name, bool AbortOnFailure) {
656 return (void *)getSymbolAddress(Name);
657}
658
662
663 for (AllocationRecord &record : m_records) {
664 if (local_address >= record.m_host_address &&
665 local_address < record.m_host_address + record.m_size) {
666 if (record.m_process_address == LLDB_INVALID_ADDRESS)
668
669 lldb::addr_t ret =
670 record.m_process_address + (local_address - record.m_host_address);
671
672 LLDB_LOGF(log,
673 "IRExecutionUnit::GetRemoteAddressForLocal() found 0x%" PRIx64
674 " in [0x%" PRIx64 "..0x%" PRIx64 "], and returned 0x%" PRIx64
675 " from [0x%" PRIx64 "..0x%" PRIx64 "].",
676 local_address, (uint64_t)record.m_host_address,
677 (uint64_t)record.m_host_address + (uint64_t)record.m_size, ret,
678 record.m_process_address,
679 record.m_process_address + record.m_size);
680
681 return ret;
682 }
683 }
684
686}
687
690 for (AllocationRecord &record : m_records) {
691 if (local_address >= record.m_host_address &&
692 local_address < record.m_host_address + record.m_size) {
693 if (record.m_process_address == LLDB_INVALID_ADDRESS)
694 return AddrRange(0, 0);
695
696 return AddrRange(record.m_process_address, record.m_size);
697 }
698 }
699
700 return AddrRange(0, 0);
701}
702
704 Status &error,
705 AllocationRecord &record) {
707 return true;
708 }
709
710 switch (record.m_sect_type) {
732 error.Clear();
733 break;
734 default:
735 const bool zero_memory = false;
736 if (auto address_or_error =
737 Malloc(record.m_size, record.m_alignment, record.m_permissions,
738 eAllocationPolicyProcessOnly, zero_memory))
739 record.m_process_address = *address_or_error;
740 else
741 error = Status::FromError(address_or_error.takeError());
742 break;
743 }
744
745 return error.Success();
746}
747
749 bool ret = true;
750
752
753 for (AllocationRecord &record : m_records) {
754 ret = CommitOneAllocation(process_sp, err, record);
755
756 if (!ret) {
757 break;
758 }
759 }
760
761 if (!ret) {
762 for (AllocationRecord &record : m_records) {
763 if (record.m_process_address != LLDB_INVALID_ADDRESS) {
764 Free(record.m_process_address, err);
765 record.m_process_address = LLDB_INVALID_ADDRESS;
766 }
767 }
768 }
769
770 return ret;
771}
772
773void IRExecutionUnit::ReportAllocations(llvm::ExecutionEngine &engine) {
775
776 for (AllocationRecord &record : m_records) {
777 if (record.m_process_address == LLDB_INVALID_ADDRESS)
778 continue;
779
780 if (record.m_section_id == eSectionIDInvalid)
781 continue;
782
783 engine.mapSectionAddress((void *)record.m_host_address,
784 record.m_process_address);
785 }
786
787 // Trigger re-application of relocations.
788 engine.finalizeObject();
789}
790
792 bool wrote_something = false;
793 for (AllocationRecord &record : m_records) {
794 if (record.m_process_address != LLDB_INVALID_ADDRESS) {
796 WriteMemory(record.m_process_address, (uint8_t *)record.m_host_address,
797 record.m_size, err);
798 if (err.Success())
799 wrote_something = true;
800 }
801 }
802 return wrote_something;
803}
804
806 if (!log)
807 return;
808
809 LLDB_LOGF(log,
810 "[0x%llx+0x%llx]->0x%llx (alignment %d, section ID %d, name %s)",
811 (unsigned long long)m_host_address, (unsigned long long)m_size,
812 (unsigned long long)m_process_address, (unsigned)m_alignment,
813 (unsigned)m_section_id, m_name.c_str());
814}
815
820
825
827 lldb_private::Symtab &symtab) {
828 // No symbols yet...
829}
830
832 lldb_private::ObjectFile *obj_file,
833 lldb_private::SectionList &section_list) {
834 for (AllocationRecord &record : m_records) {
835 if (record.m_size > 0) {
836 lldb::SectionSP section_sp = std::make_shared<Section>(
837 obj_file->GetModule(), obj_file, record.m_section_id, record.m_name,
838 record.m_sect_type, record.m_process_address, record.m_size,
839 record.m_host_address, // file_offset (which is the host address for
840 // the data)
841 record.m_size, // file_size
842 0,
843 record.m_permissions); // flags
844 section_list.AddSection(section_sp);
845 }
846 }
847}
848
851 if(Target *target = exe_ctx.GetTargetPtr())
852 return target->GetArchitecture();
853 return ArchSpec();
854}
855
858 Target *target = exe_ctx.GetTargetPtr();
859 if (!target)
860 return nullptr;
861
862 auto Delegate = std::static_pointer_cast<lldb_private::ObjectFileJITDelegate>(
863 shared_from_this());
864
865 lldb::ModuleSP jit_module_sp =
867 if (!jit_module_sp)
868 return nullptr;
869
870 bool changed = false;
871 jit_module_sp->SetLoadAddress(*target, 0, true, changed);
872 return jit_module_sp;
873}
static llvm::raw_ostream & error(Stream &strm)
#define lldbassert(x)
Definition LLDBAssert.h:16
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
Definition Log.h:375
#define LLDB_LOGF(log,...)
Definition Log.h:389
A section + offset based address class.
Definition Address.h:62
An architecture specification class.
Definition ArchSpec.h:32
uint32_t GetAddressByteSize() const
Returns the size in bytes of an address of the current architecture.
Definition ArchSpec.cpp:710
const char * GetArchitectureName() const
Returns a static string representing the current architecture.
Definition ArchSpec.cpp:568
A uniqued constant string class.
Definition ConstString.h:40
A subclass of DataBuffer that stores a data buffer on the heap.
lldb::offset_t GetByteSize() const override
Get the number of bytes in the data buffer.
An data extractor class.
virtual uint64_t GetByteSize() const
Get the number of bytes contained in this object.
@ TypeUInt8
Format output as unsigned 8 bit integers.
lldb::offset_t PutToLog(Log *log, lldb::offset_t offset, lldb::offset_t length, uint64_t base_addr, uint32_t num_per_line, Type type) const
Dumps the binary data as type objects to stream s (or to Log() if s is nullptr) starting offset bytes...
static lldb::DisassemblerSP FindPlugin(const ArchSpec &arch, const char *flavor, const char *cpu, const char *features, const char *plugin_name)
"lldb/Target/ExecutionContext.h" A class that contains an execution context.
lldb::ByteOrder GetByteOrder() const
Target * GetTargetPtr() const
Returns a pointer to the target object.
Process * GetProcessPtr() const
Returns a pointer to the process object.
A file utility class.
Definition FileSpec.h:56
FileSpec CopyByAppendingPathComponent(llvm::StringRef component) const
Definition FileSpec.cpp:425
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
Definition FileSpec.cpp:380
void * getPointerToNamedFunction(const std::string &Name, bool AbortOnFailure=true) override
std::unique_ptr< SectionMemoryManager > m_default_mm_up
The memory allocator to use in actually creating space.
uint64_t getSymbolAddress(const std::string &Name) override
uint8_t * allocateDataSection(uintptr_t Size, unsigned Alignment, unsigned SectionID, llvm::StringRef SectionName, bool IsReadOnly) override
Allocate space for data, and add it to the m_spaceBlocks map.
IRExecutionUnit & m_parent
The execution unit this is a proxy for.
uint64_t GetSymbolAddressAndPresence(const std::string &Name, bool &missing_weak)
llvm::JITSymbol findSymbol(const std::string &Name) override
uint8_t * allocateCodeSection(uintptr_t Size, unsigned Alignment, unsigned SectionID, llvm::StringRef SectionName) override
Allocate space for executable code, and add it to the m_spaceBlocks map.
std::vector< std::string > m_cpu_features
static const unsigned eSectionIDInvalid
void PopulateSymtab(lldb_private::ObjectFile *obj_file, lldb_private::Symtab &symtab) override
void GetRunnableInfo(Status &error, lldb::addr_t &func_addr, lldb::addr_t &func_end)
lldb::ByteOrder GetByteOrder() const override
ObjectFileJITDelegate overrides.
std::vector< JittedFunction > m_jitted_functions
A vector of all functions that have been JITted into machine code.
Status DisassembleFunction(Stream &stream, lldb::ProcessSP &process_sp)
std::vector< ConstString > m_failed_lookups
std::unique_ptr< llvm::Module > m_module_up
Holder for the module until it's been handed off.
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)
Constructor.
static lldb::SectionType GetSectionTypeFromSectionName(const llvm::StringRef &name, AllocationKind alloc_kind)
uint32_t GetAddressByteSize() const override
bool CommitAllocations(lldb::ProcessSP &process_sp)
Commit all allocations to the process and record where they were stored.
bool CommitOneAllocation(lldb::ProcessSP &process_sp, Status &error, AllocationRecord &record)
void GetStaticInitializers(std::vector< lldb::addr_t > &static_initializers)
std::unique_ptr< llvm::ExecutionEngine > m_execution_engine_up
llvm::Module * m_module
Owned by the execution engine.
std::unique_ptr< llvm::LLVMContext > m_context_up
ArchSpec GetArchitecture() override
AddrRange GetRemoteRangeForLocal(lldb::addr_t local_address)
Look up the object in m_address_map that contains a given address, find where it was copied to,...
void ReportSymbolLookupError(ConstString name)
void PopulateSectionList(lldb_private::ObjectFile *obj_file, lldb_private::SectionList &section_list) override
std::pair< lldb::addr_t, uintptr_t > AddrRange
std::vector< JittedGlobalVariable > m_jitted_global_variables
A vector of all functions that have been JITted into machine code.
bool WriteData(lldb::ProcessSP &process_sp)
Write the contents of all allocations to the process.
std::unique_ptr< llvm::ObjectCache > m_object_cache_up
ExternalSymbolResolver m_external_symbol_resolver
~IRExecutionUnit() override
Destructor.
void ReportAllocations(llvm::ExecutionEngine &engine)
Report all committed allocations to the execution engine.
lldb::addr_t GetRemoteAddressForLocal(lldb::addr_t local_address)
Look up the object in m_address_map that contains a given address, find where it was copied to,...
bool m_reported_allocations
True after allocations have been reported.
void Free(lldb::addr_t process_address, Status &error)
llvm::Expected< lldb::addr_t > Malloc(size_t size, uint8_t alignment, uint32_t permissions, AllocationPolicy policy, bool zero_memory, AllocationPolicy *used_policy=nullptr)
ExecutionContextScope * GetBestExecutionContextScope() const
lldb::ProcessWP & GetProcessWP()
Definition IRMemoryMap.h:92
IRMemoryMap(lldb::TargetSP target_sp)
void WriteMemory(lldb::addr_t process_address, const uint8_t *bytes, size_t size, Status &error)
void ReadMemory(uint8_t *bytes, lldb::addr_t process_address, size_t size, Status &error)
@ eAllocationPolicyProcessOnly
The intent is that this allocation exist only in the process.
Definition IRMemoryMap.h:50
void Dump(Stream *s, bool show_address, bool show_bytes, bool show_control_flow_kind, const ExecutionContext *exe_ctx)
A class that handles mangled names.
Definition Mangled.h:36
lldb::ModuleSP GetModule() const
Get const accessor for the module pointer.
static lldb::ModuleSP CreateModuleFromObjectFile(Args &&...args)
Definition Module.h:137
A plug-in interface definition class for object file parsers.
Definition ObjectFile.h:46
static lldb::SectionType GetDWARFSectionTypeFromName(llvm::StringRef name)
Parses the section type from a section name for DWARF sections.
A plug-in interface definition class for debugging a process.
Definition Process.h:369
size_t ReadMemory(const ProcessAddress &process_addr, void *buf, size_t size, Status &error)
Read of memory from a process.
Definition Process.cpp:2114
lldb::ByteOrder GetByteOrder() const
Definition Process.cpp:3969
size_t AddSection(const lldb::SectionSP &section_sp)
Definition Section.cpp:483
An error handling class.
Definition Status.h:118
void Clear()
Clear the object state.
Definition Status.cpp:214
static Status FromErrorStringWithFormat(const char *format,...) __attribute__((format(printf
Definition Status.cpp:106
static Status FromErrorString(const char *str)
Definition Status.h:141
const char * AsCString(const char *default_error_str="unknown error") const
Get the error string associated with the current error.
Definition Status.cpp:194
static Status static Status FromErrorStringWithFormatv(const char *format, Args &&...args)
Definition Status.h:151
static Status FromError(llvm::Error error)
Avoid using this in new code. Migrate APIs to llvm::Expected instead.
Definition Status.cpp:136
bool Success() const
Test for success condition.
Definition Status.cpp:303
const char * GetData() const
llvm::StringRef GetString() const
A stream class that can stream formatted output to a file.
Definition Stream.h:28
size_t PutCString(llvm::StringRef cstr)
Output a C string to the stream.
Definition Stream.cpp:63
Defines a symbol context baton that can be handed other debug core functions.
const ArchSpec & GetArchitecture() const
Definition Target.h:1325
uint8_t * GetBytes()
Get a pointer to the data.
Definition DataBuffer.h:108
#define LLDB_INVALID_ADDRESS
#define UINT32_MAX
A class that represents a running process on the host machine.
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
Definition Log.h:338
std::shared_ptr< lldb_private::Process > ProcessSP
std::shared_ptr< lldb_private::Disassembler > DisassemblerSP
ByteOrder
Byte ordering definitions.
std::shared_ptr< lldb_private::Section > SectionSP
std::shared_ptr< lldb_private::WritableDataBuffer > WritableDataBufferSP
uint64_t addr_t
Definition lldb-types.h:80
std::shared_ptr< lldb_private::Target > TargetSP
@ eSectionTypeDWARFDebugStrOffsets
@ eSectionTypeInvalid
@ eSectionTypeDWARFDebugPubNames
@ eSectionTypeDWARFDebugFrame
@ eSectionTypeDWARFDebugLocLists
DWARF v5 .debug_loclists.
@ eSectionTypeDWARFDebugMacInfo
@ eSectionTypeDWARFAppleNamespaces
@ eSectionTypeDWARFAppleTypes
@ eSectionTypeDWARFDebugInfo
@ eSectionTypeDWARFDebugRanges
@ eSectionTypeDWARFDebugLine
@ eSectionTypeDWARFDebugPubTypes
@ eSectionTypeDWARFDebugStr
@ eSectionTypeDWARFDebugLoc
@ eSectionTypeDWARFAppleNames
@ eSectionTypeDWARFAppleObjC
@ eSectionTypeDWARFDebugCuIndex
@ eSectionTypeDWARFDebugAranges
@ eSectionTypeDWARFGNUDebugAltLink
@ eSectionTypeDWARFDebugAbbrev
@ eSectionTypeDWARFDebugAddr
std::shared_ptr< lldb_private::Module > ModuleSP
Encapsulates a single allocation request made by the JIT.
"lldb/Expression/IRExecutionUnit.h" Encapsulates a single function that has been generated by the JIT...