LLDB mainline
IRInterpreter.cpp
Go to the documentation of this file.
1//===-- IRInterpreter.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
10#include "lldb/Core/Debugger.h"
11#include "lldb/Core/Module.h"
18#include "lldb/Utility/Endian.h"
20#include "lldb/Utility/Log.h"
21#include "lldb/Utility/Policy.h"
22#include "lldb/Utility/Scalar.h"
23#include "lldb/Utility/Status.h"
26
27#include "lldb/Target/ABI.h"
29#include "lldb/Target/Target.h"
30#include "lldb/Target/Thread.h"
33
34#include "llvm/IR/Constants.h"
35#include "llvm/IR/DataLayout.h"
36#include "llvm/IR/Function.h"
37#include "llvm/IR/Instructions.h"
38#include "llvm/IR/Intrinsics.h"
39#include "llvm/IR/LLVMContext.h"
40#include "llvm/IR/Module.h"
41#include "llvm/IR/Operator.h"
42#include "llvm/Support/raw_ostream.h"
43
44#include <map>
45
46using namespace llvm;
48
49static std::string PrintValue(const Value *value, bool truncate = false) {
50 std::string s;
51 raw_string_ostream rso(s);
52 value->print(rso);
53 if (truncate)
54 s.resize(s.length() - 1);
55
56 size_t offset;
57 while ((offset = s.find('\n')) != s.npos)
58 s.erase(offset, 1);
59 while (s[0] == ' ' || s[0] == '\t')
60 s.erase(0, 1);
61
62 return s;
63}
64
65static std::string PrintType(const Type *type, bool truncate = false) {
66 std::string s;
67 raw_string_ostream rso(s);
68 type->print(rso);
69 if (truncate)
70 s.resize(s.length() - 1);
71 return s;
72}
73
74static bool CanIgnoreCall(const CallInst *call) {
75 const llvm::Function *called_function = call->getCalledFunction();
76
77 if (!called_function)
78 return false;
79
80 if (called_function->isIntrinsic()) {
81 switch (called_function->getIntrinsicID()) {
82 default:
83 break;
84 case llvm::Intrinsic::dbg_declare:
85 case llvm::Intrinsic::dbg_value:
86 case llvm::Intrinsic::ptrauth_auth:
87 case llvm::Intrinsic::ptrauth_blend:
88 case llvm::Intrinsic::ptrauth_strip:
89 return true;
90 }
91 }
92
93 return false;
94}
95
97public:
98 typedef std::map<const Value *, lldb::addr_t> ValueMap;
99
101 const DataLayout &m_target_data;
103 const BasicBlock *m_bb = nullptr;
104 const BasicBlock *m_prev_bb = nullptr;
105 BasicBlock::const_iterator m_ii;
106 BasicBlock::const_iterator m_ie;
107
111
114
115 InterpreterStackFrame(const DataLayout &target_data,
116 lldb_private::IRExecutionUnit &execution_unit,
117 lldb::addr_t stack_frame_bottom,
118 lldb::addr_t stack_frame_top)
119 : m_target_data(target_data), m_execution_unit(execution_unit) {
120 m_byte_order = (target_data.isLittleEndian() ? lldb::eByteOrderLittle
122 m_addr_byte_size = (target_data.getPointerSize(0));
123
124 m_frame_process_address = stack_frame_bottom;
125 m_frame_size = stack_frame_top - stack_frame_bottom;
126 m_stack_pointer = stack_frame_top;
127 }
128
130
131 void Jump(const BasicBlock *bb) {
132 m_prev_bb = m_bb;
133 m_bb = bb;
134 m_ii = m_bb->begin();
135 m_ie = m_bb->end();
136 }
137
138 std::string SummarizeValue(const Value *value) {
140
141 ss.PutCString(PrintValue(value).c_str());
142
143 ValueMap::iterator i = m_values.find(value);
144
145 if (i != m_values.end()) {
146 lldb::addr_t addr = i->second;
147
148 ss.Printf(" 0x%llx", (unsigned long long)addr);
149 }
150
151 return std::string(ss.GetString());
152 }
153
154 bool AssignToMatchType(lldb_private::Scalar &scalar, llvm::APInt value,
155 Type *type) {
156 size_t type_size = m_target_data.getTypeStoreSize(type);
157
158 if (type_size > 8)
159 return false;
160
161 if (type_size != 1)
162 type_size = PowerOf2Ceil(type_size);
163
164 scalar = value.zextOrTrunc(type_size * 8);
165 return true;
166 }
167
168 bool EvaluateValue(lldb_private::Scalar &scalar, const Value *value,
169 Module &module) {
170 const Constant *constant = dyn_cast<Constant>(value);
171
172 if (constant) {
173 if (constant->getValueID() == Value::ConstantFPVal) {
174 if (auto *cfp = dyn_cast<ConstantFP>(constant)) {
175 if (cfp->getType()->isDoubleTy())
176 scalar = cfp->getValueAPF().convertToDouble();
177 else if (cfp->getType()->isFloatTy())
178 scalar = cfp->getValueAPF().convertToFloat();
179 else
180 return false;
181 return true;
182 }
183 return false;
184 }
185 APInt value_apint;
186
187 if (!ResolveConstantValue(value_apint, constant))
188 return false;
189
190 return AssignToMatchType(scalar, value_apint, value->getType());
191 }
192
193 lldb::addr_t process_address = ResolveValue(value, module);
194 size_t value_size = m_target_data.getTypeStoreSize(value->getType());
195
196 lldb_private::DataExtractor value_extractor;
197 lldb_private::Status extract_error;
198
199 m_execution_unit.GetMemoryData(value_extractor, process_address,
200 value_size, extract_error);
201
202 if (!extract_error.Success())
203 return false;
204
205 lldb::offset_t offset = 0;
206 if (value_size <= 8) {
207 Type *ty = value->getType();
208 if (ty->isDoubleTy()) {
209 scalar = value_extractor.GetDouble(&offset);
210 return true;
211 } else if (ty->isFloatTy()) {
212 scalar = value_extractor.GetFloat(&offset);
213 return true;
214 } else {
215 uint64_t u64value = value_extractor.GetMaxU64(&offset, value_size);
216 return AssignToMatchType(scalar, llvm::APInt(64, u64value),
217 value->getType());
218 }
219 }
220
221 return false;
222 }
223
224 bool AssignValue(const Value *value, lldb_private::Scalar scalar,
225 Module &module) {
226 lldb::addr_t process_address = ResolveValue(value, module);
227
228 if (process_address == LLDB_INVALID_ADDRESS)
229 return false;
230
231 lldb_private::Scalar cast_scalar;
232 Type *vty = value->getType();
233 if (vty->isFloatTy() || vty->isDoubleTy()) {
234 cast_scalar = scalar;
235 } else {
236 scalar.MakeUnsigned();
237 if (!AssignToMatchType(cast_scalar, scalar.UInt128(llvm::APInt()),
238 value->getType()))
239 return false;
240 }
241
242 size_t value_byte_size = m_target_data.getTypeStoreSize(value->getType());
243
244 lldb_private::DataBufferHeap buf(value_byte_size, 0);
245
246 lldb_private::Status get_data_error;
247
248 if (!cast_scalar.GetAsMemoryData(buf.GetBytes(), buf.GetByteSize(),
249 m_byte_order, get_data_error))
250 return false;
251
252 lldb_private::Status write_error;
253
254 m_execution_unit.WriteMemory(process_address, buf.GetBytes(),
255 buf.GetByteSize(), write_error);
256
257 return write_error.Success();
258 }
259
260 bool ResolveConstantValue(APInt &value, const Constant *constant) {
261 switch (constant->getValueID()) {
262 default:
263 break;
264 case Value::FunctionVal:
265 if (const Function *constant_func = dyn_cast<Function>(constant)) {
267 llvm::GlobalValue::dropLLVMManglingEscape(
268 constant_func->getName()));
269 bool missing_weak = false;
270 lldb::addr_t addr = m_execution_unit.FindSymbol(name, missing_weak);
271 if (addr == LLDB_INVALID_ADDRESS)
272 return false;
273 // A resolved symbol address may be wider than a target pointer when we
274 // store extra information in the high bits, such as an address-space
275 // tag. Truncate to the pointer width rather than asserting. When the
276 // address already fits this is a no-op.
277 value = APInt(m_target_data.getPointerSizeInBits(), addr,
278 /*isSigned=*/false, /*implicitTrunc=*/true);
279 return true;
280 }
281 break;
282 case Value::ConstantIntVal:
283 if (const ConstantInt *constant_int = dyn_cast<ConstantInt>(constant)) {
284 value = constant_int->getValue();
285 return true;
286 }
287 break;
288 case Value::ConstantFPVal:
289 if (const ConstantFP *constant_fp = dyn_cast<ConstantFP>(constant)) {
290 value = constant_fp->getValueAPF().bitcastToAPInt();
291 return true;
292 }
293 break;
294 case Value::ConstantExprVal:
295 if (const ConstantExpr *constant_expr =
296 dyn_cast<ConstantExpr>(constant)) {
297 switch (constant_expr->getOpcode()) {
298 default:
299 return false;
300 case Instruction::IntToPtr:
301 case Instruction::PtrToInt:
302 case Instruction::BitCast:
303 return ResolveConstantValue(value, constant_expr->getOperand(0));
304 case Instruction::GetElementPtr: {
305 ConstantExpr::const_op_iterator op_cursor = constant_expr->op_begin();
306 ConstantExpr::const_op_iterator op_end = constant_expr->op_end();
307
308 Constant *base = dyn_cast<Constant>(*op_cursor);
309
310 if (!base)
311 return false;
312
313 if (!ResolveConstantValue(value, base))
314 return false;
315
316 op_cursor++;
317
318 if (op_cursor == op_end)
319 return true; // no offset to apply!
320
321 SmallVector<Value *, 8> indices(op_cursor, op_end);
322 Type *src_elem_ty =
323 cast<GEPOperator>(constant_expr)->getSourceElementType();
324
325 // DataLayout::getIndexedOffsetInType assumes the indices are
326 // instances of ConstantInt.
327 uint64_t offset =
328 m_target_data.getIndexedOffsetInType(src_elem_ty, indices);
329
330 const bool is_signed = true;
331 value += APInt(value.getBitWidth(), offset, is_signed);
332
333 return true;
334 }
335 }
336 }
337 break;
338 case Value::ConstantPointerNullVal:
339 if (isa<ConstantPointerNull>(constant)) {
340 value = APInt(m_target_data.getPointerSizeInBits(), 0);
341 return true;
342 }
343 break;
344 }
345 return false;
346 }
347
348 bool MakeArgument(const Argument *value, uint64_t address) {
349 lldb::addr_t data_address = Malloc(value->getType());
350
351 if (data_address == LLDB_INVALID_ADDRESS)
352 return false;
353
354 lldb_private::Status write_error;
355
356 m_execution_unit.WritePointerToMemory(data_address, address, write_error);
357
358 if (!write_error.Success()) {
359 lldb_private::Status free_error;
360 m_execution_unit.Free(data_address, free_error);
361 return false;
362 }
363
364 m_values[value] = data_address;
365
366 lldb_private::Log *log(GetLog(LLDBLog::Expressions));
367
368 LLDB_LOGF(log, "Made an allocation for argument %s",
369 PrintValue(value).c_str());
370 LLDB_LOGF(log, " Data region : %llx", (unsigned long long)address);
371 LLDB_LOGF(log, " Ref region : %llx", (unsigned long long)data_address);
372
373 return true;
374 }
375
376 bool ResolveConstant(lldb::addr_t process_address, const Constant *constant) {
377 APInt resolved_value;
378
379 if (!ResolveConstantValue(resolved_value, constant))
380 return false;
381
382 size_t constant_size = m_target_data.getTypeStoreSize(constant->getType());
383 lldb_private::DataBufferHeap buf(constant_size, 0);
384
385 lldb_private::Status get_data_error;
386
387 lldb_private::Scalar resolved_scalar(
388 resolved_value.zextOrTrunc(llvm::NextPowerOf2(constant_size) * 8));
389 if (!resolved_scalar.GetAsMemoryData(buf.GetBytes(), buf.GetByteSize(),
390 m_byte_order, get_data_error))
391 return false;
392
393 lldb_private::Status write_error;
394
395 m_execution_unit.WriteMemory(process_address, buf.GetBytes(),
396 buf.GetByteSize(), write_error);
397
398 return write_error.Success();
399 }
400
401 lldb::addr_t Malloc(size_t size, uint8_t byte_alignment) {
403
404 ret -= size;
405 ret -= (ret % byte_alignment);
406
407 if (ret < m_frame_process_address)
409
410 m_stack_pointer = ret;
411 return ret;
412 }
413
414 lldb::addr_t Malloc(llvm::Type *type) {
415 lldb_private::Status alloc_error;
416
417 return Malloc(m_target_data.getTypeAllocSize(type),
418 m_target_data.getPrefTypeAlign(type).value());
419 }
420
421 std::string PrintData(lldb::addr_t addr, llvm::Type *type) {
422 size_t length = m_target_data.getTypeStoreSize(type);
423
424 lldb_private::DataBufferHeap buf(length, 0);
425
426 lldb_private::Status read_error;
427
428 m_execution_unit.ReadMemory(buf.GetBytes(), addr, length, read_error);
429
430 if (!read_error.Success())
431 return std::string("<couldn't read data>");
432
434
435 for (size_t i = 0; i < length; i++) {
436 if ((!(i & 0xf)) && i)
437 ss.Printf("%02hhx - ", buf.GetBytes()[i]);
438 else
439 ss.Printf("%02hhx ", buf.GetBytes()[i]);
440 }
441
442 return std::string(ss.GetString());
443 }
444
445 lldb::addr_t ResolveValue(const Value *value, Module &module) {
446 ValueMap::iterator i = m_values.find(value);
447
448 if (i != m_values.end())
449 return i->second;
450
451 // Fall back and allocate space [allocation type Alloca]
452
453 lldb::addr_t data_address = Malloc(value->getType());
454
455 if (const Constant *constant = dyn_cast<Constant>(value)) {
456 if (!ResolveConstant(data_address, constant)) {
457 lldb_private::Status free_error;
458 m_execution_unit.Free(data_address, free_error);
460 }
461 }
462
463 m_values[value] = data_address;
464 return data_address;
465 }
466};
467
468static const char *unsupported_opcode_error =
469 "Interpreter doesn't handle one of the expression's opcodes";
470static const char *unsupported_operand_error =
471 "Interpreter doesn't handle one of the expression's operands";
472static const char *interpreter_internal_error =
473 "Interpreter encountered an internal error";
474static const char *interrupt_error =
475 "Interrupted while interpreting expression";
476static const char *bad_value_error =
477 "Interpreter couldn't resolve a value during execution";
478static const char *memory_allocation_error =
479 "Interpreter couldn't allocate memory";
480static const char *memory_write_error = "Interpreter couldn't write to memory";
481static const char *memory_read_error = "Interpreter couldn't read from memory";
482static const char *timeout_error =
483 "Reached timeout while interpreting expression";
484static const char *too_many_functions_error =
485 "Interpreter doesn't handle modules with multiple function bodies.";
486
487static bool CanResolveConstant(llvm::Constant *constant) {
488 switch (constant->getValueID()) {
489 default:
490 return false;
491 case Value::ConstantIntVal:
492 case Value::ConstantFPVal:
493 case Value::FunctionVal:
494 return true;
495 case Value::ConstantExprVal:
496 if (const ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(constant)) {
497 switch (constant_expr->getOpcode()) {
498 default:
499 return false;
500 case Instruction::IntToPtr:
501 case Instruction::PtrToInt:
502 case Instruction::BitCast:
503 return CanResolveConstant(constant_expr->getOperand(0));
504 case Instruction::GetElementPtr: {
505 // Check that the base can be constant-resolved.
506 ConstantExpr::const_op_iterator op_cursor = constant_expr->op_begin();
507 Constant *base = dyn_cast<Constant>(*op_cursor);
508 if (!base || !CanResolveConstant(base))
509 return false;
510
511 // Check that all other operands are just ConstantInt.
512 for (Value *op : make_range(constant_expr->op_begin() + 1,
513 constant_expr->op_end())) {
514 ConstantInt *constant_int = dyn_cast<ConstantInt>(op);
515 if (!constant_int)
516 return false;
517 }
518 return true;
519 }
520 }
521 } else {
522 return false;
523 }
524 case Value::ConstantPointerNullVal:
525 return true;
526 }
527}
528
529bool IRInterpreter::CanInterpret(llvm::Module &module, llvm::Function &function,
531 const bool support_function_calls) {
532 lldb_private::Log *log(GetLog(LLDBLog::Expressions));
533
534 bool saw_function_with_body = false;
535 for (Function &f : module) {
536 if (f.begin() != f.end()) {
537 if (saw_function_with_body) {
538 LLDB_LOGF(log, "More than one function in the module has a body");
540 return false;
541 }
542 saw_function_with_body = true;
543 LLDB_LOGF(log, "Saw function with body: %s", f.getName().str().c_str());
544 }
545 }
546
547 for (BasicBlock &bb : function) {
548 for (Instruction &ii : bb) {
549 switch (ii.getOpcode()) {
550 default: {
551 LLDB_LOGF(log, "Unsupported instruction: %s", PrintValue(&ii).c_str());
553 return false;
554 }
555 case Instruction::Add:
556 case Instruction::Alloca:
557 case Instruction::BitCast:
558 case Instruction::UncondBr:
559 case Instruction::CondBr:
560 case Instruction::PHI:
561 break;
562 case Instruction::Call: {
563 CallInst *call_inst = dyn_cast<CallInst>(&ii);
564
565 if (!call_inst) {
566 error =
568 return false;
569 }
570
571 if (!CanIgnoreCall(call_inst) && !support_function_calls) {
572 LLDB_LOGF(log, "Unsupported instruction: %s",
573 PrintValue(&ii).c_str());
574 error =
576 return false;
577 }
578 } break;
579 case Instruction::GetElementPtr:
580 break;
581 case Instruction::FCmp:
582 case Instruction::ICmp: {
583 CmpInst *cmp_inst = dyn_cast<CmpInst>(&ii);
584
585 if (!cmp_inst) {
586 error =
588 return false;
589 }
590
591 switch (cmp_inst->getPredicate()) {
592 default: {
593 LLDB_LOGF(log, "Unsupported ICmp predicate: %s",
594 PrintValue(&ii).c_str());
595
596 error =
598 return false;
599 }
600 case CmpInst::FCMP_OEQ:
601 case CmpInst::ICMP_EQ:
602 case CmpInst::FCMP_UNE:
603 case CmpInst::ICMP_NE:
604 case CmpInst::FCMP_OGT:
605 case CmpInst::ICMP_UGT:
606 case CmpInst::FCMP_OGE:
607 case CmpInst::ICMP_UGE:
608 case CmpInst::FCMP_OLT:
609 case CmpInst::ICMP_ULT:
610 case CmpInst::FCMP_OLE:
611 case CmpInst::ICMP_ULE:
612 case CmpInst::ICMP_SGT:
613 case CmpInst::ICMP_SGE:
614 case CmpInst::ICMP_SLT:
615 case CmpInst::ICMP_SLE:
616 break;
617 }
618 } break;
619 case Instruction::And:
620 case Instruction::AShr:
621 case Instruction::FPToUI:
622 case Instruction::FPToSI:
623 case Instruction::IntToPtr:
624 case Instruction::PtrToInt:
625 case Instruction::Load:
626 case Instruction::LShr:
627 case Instruction::Mul:
628 case Instruction::Or:
629 case Instruction::Ret:
630 case Instruction::SDiv:
631 case Instruction::SExt:
632 case Instruction::Shl:
633 case Instruction::SRem:
634 case Instruction::Store:
635 case Instruction::Sub:
636 case Instruction::Trunc:
637 case Instruction::UDiv:
638 case Instruction::URem:
639 case Instruction::Xor:
640 case Instruction::ZExt:
641 break;
642 case Instruction::FAdd:
643 case Instruction::FSub:
644 case Instruction::FMul:
645 case Instruction::FDiv:
646 break;
647 case Instruction::UIToFP:
648 case Instruction::SIToFP:
649 case Instruction::FPTrunc:
650 case Instruction::FPExt:
651 if (!ii.getType()->isFloatTy() && !ii.getType()->isDoubleTy()) {
652 LLDB_LOGF(log, "Unsupported instruction: %s",
653 PrintValue(&ii).c_str());
654 error =
656 return false;
657 }
658 break;
659 }
660
661 for (unsigned oi = 0, oe = ii.getNumOperands(); oi != oe; ++oi) {
662 Value *operand = ii.getOperand(oi);
663 Type *operand_type = operand->getType();
664
665 switch (operand_type->getTypeID()) {
666 default:
667 break;
668 case Type::FixedVectorTyID:
669 case Type::ScalableVectorTyID: {
670 LLDB_LOGF(log, "Unsupported operand type: %s",
671 PrintType(operand_type).c_str());
672 error =
674 return false;
675 }
676 }
677
678 // The IR interpreter currently doesn't know about
679 // 128-bit integers. As they're not that frequent,
680 // we can just fall back to the JIT rather than
681 // choking.
682 if (operand_type->getPrimitiveSizeInBits() > 64) {
683 LLDB_LOGF(log, "Unsupported operand type: %s",
684 PrintType(operand_type).c_str());
685 error =
687 return false;
688 }
689
690 if (Constant *constant = llvm::dyn_cast<Constant>(operand)) {
691 if (!CanResolveConstant(constant)) {
692 LLDB_LOGF(log, "Unsupported constant: %s",
693 PrintValue(constant).c_str());
696 return false;
697 }
698 }
699 }
700 }
701 }
702
703 return true;
704}
705
706bool IRInterpreter::Interpret(llvm::Module &module, llvm::Function &function,
707 llvm::ArrayRef<lldb::addr_t> args,
708 lldb_private::IRExecutionUnit &execution_unit,
710 lldb::addr_t stack_frame_bottom,
711 lldb::addr_t stack_frame_top,
714 lldb_private::Log *log(GetLog(LLDBLog::Expressions));
715
716 if (log) {
717 std::string s;
718 raw_string_ostream oss(s);
719
720 module.print(oss, nullptr);
721
722 LLDB_LOGF(log, "Module as passed in to IRInterpreter::Interpret: \n\"%s\"",
723 s.c_str());
724 }
725
726 const DataLayout &data_layout = module.getDataLayout();
727
728 InterpreterStackFrame frame(data_layout, execution_unit, stack_frame_bottom,
729 stack_frame_top);
730
732 error =
733 lldb_private::Status::FromErrorString("Couldn't allocate stack frame");
734 }
735
736 int arg_index = 0;
737
738 for (llvm::Function::arg_iterator ai = function.arg_begin(),
739 ae = function.arg_end();
740 ai != ae; ++ai, ++arg_index) {
741 if (args.size() <= static_cast<size_t>(arg_index)) {
743 "Not enough arguments passed in to function");
744 return false;
745 }
746
747 lldb::addr_t ptr = args[arg_index];
748
749 frame.MakeArgument(&*ai, ptr);
750 }
751
752 frame.Jump(&function.front());
753
754 lldb_private::Process *process = exe_ctx.GetProcessPtr();
755 lldb_private::Target *target = exe_ctx.GetTargetPtr();
756
757 using clock = std::chrono::steady_clock;
758
759 // Compute the time at which the timeout has been exceeded.
760 std::optional<clock::time_point> end_time;
761 if (timeout && timeout->count() > 0)
762 end_time = clock::now() + *timeout;
763
764 while (frame.m_ii != frame.m_ie) {
765 // Timeout reached: stop interpreting.
766 if (end_time && clock::now() >= *end_time) {
768 return false;
769 }
770
771 // If we have access to the debugger we can honor an interrupt request.
772 if (target) {
773 if (INTERRUPT_REQUESTED(target->GetDebugger(),
774 "Interrupted in IR interpreting.")) {
776 return false;
777 }
778 }
779
780 const Instruction *inst = &*frame.m_ii;
781
782 LLDB_LOGF(log, "Interpreting %s", PrintValue(inst).c_str());
783
784 switch (inst->getOpcode()) {
785 default:
786 break;
787
788 case Instruction::Add:
789 case Instruction::Sub:
790 case Instruction::Mul:
791 case Instruction::SDiv:
792 case Instruction::UDiv:
793 case Instruction::SRem:
794 case Instruction::URem:
795 case Instruction::Shl:
796 case Instruction::LShr:
797 case Instruction::AShr:
798 case Instruction::And:
799 case Instruction::Or:
800 case Instruction::Xor:
801 case Instruction::FAdd:
802 case Instruction::FSub:
803 case Instruction::FMul:
804 case Instruction::FDiv: {
805 const BinaryOperator *bin_op = dyn_cast<BinaryOperator>(inst);
806
807 if (!bin_op) {
808 LLDB_LOGF(
809 log,
810 "getOpcode() returns %s, but instruction is not a BinaryOperator",
811 inst->getOpcodeName());
812 error =
814 return false;
815 }
816
817 Value *lhs = inst->getOperand(0);
818 Value *rhs = inst->getOperand(1);
819
822
823 if (!frame.EvaluateValue(L, lhs, module)) {
824 LLDB_LOGF(log, "Couldn't evaluate %s", PrintValue(lhs).c_str());
826 return false;
827 }
828
829 if (!frame.EvaluateValue(R, rhs, module)) {
830 LLDB_LOGF(log, "Couldn't evaluate %s", PrintValue(rhs).c_str());
832 return false;
833 }
834
836
837 switch (inst->getOpcode()) {
838 default:
839 break;
840 case Instruction::Add:
841 case Instruction::FAdd:
842 result = L + R;
843 break;
844 case Instruction::Mul:
845 case Instruction::FMul:
846 result = L * R;
847 break;
848 case Instruction::Sub:
849 case Instruction::FSub:
850 result = L - R;
851 break;
852 case Instruction::SDiv:
853 L.MakeSigned();
854 R.MakeSigned();
855 result = L / R;
856 break;
857 case Instruction::UDiv:
858 L.MakeUnsigned();
859 R.MakeUnsigned();
860 result = L / R;
861 break;
862 case Instruction::FDiv:
863 result = L / R;
864 break;
865 case Instruction::SRem:
866 L.MakeSigned();
867 R.MakeSigned();
868 result = L % R;
869 break;
870 case Instruction::URem:
871 L.MakeUnsigned();
872 R.MakeUnsigned();
873 result = L % R;
874 break;
875 case Instruction::Shl:
876 result = L << R;
877 break;
878 case Instruction::AShr:
879 result = L >> R;
880 break;
881 case Instruction::LShr:
882 result = L;
883 result.ShiftRightLogical(R);
884 break;
885 case Instruction::And:
886 result = L & R;
887 break;
888 case Instruction::Or:
889 result = L | R;
890 break;
891 case Instruction::Xor:
892 result = L ^ R;
893 break;
894 }
895
896 frame.AssignValue(inst, result, module);
897
898 LLDB_LOGF(log, "Interpreted a %s", inst->getOpcodeName());
899 LLDB_LOGF(log, " L : %s", frame.SummarizeValue(lhs).c_str());
900 LLDB_LOGF(log, " R : %s", frame.SummarizeValue(rhs).c_str());
901 LLDB_LOGF(log, " = : %s", frame.SummarizeValue(inst).c_str());
902 } break;
903 case Instruction::Alloca: {
904 const AllocaInst *alloca_inst = cast<AllocaInst>(inst);
905
906 std::optional<TypeSize> alloca_size =
907 alloca_inst->getAllocationSize(frame.m_target_data);
908 if (!alloca_size || alloca_size->isScalable()) {
909 LLDB_LOGF(log, "AllocaInsts are not handled if size is not computable");
911 return false;
912 }
913
914 // The semantics of Alloca are:
915 // Create a region R of virtual memory of type T, backed by a data
916 // buffer
917 // Create a region P of virtual memory of type T*, backed by a data
918 // buffer
919 // Write the virtual address of R into P
920
921 Type *Tptr = alloca_inst->getType();
922
923 lldb::addr_t R = frame.Malloc(alloca_size->getFixedValue(),
924 alloca_inst->getAlign().value());
925
926 if (R == LLDB_INVALID_ADDRESS) {
927 LLDB_LOGF(log, "Couldn't allocate memory for an AllocaInst");
929 return false;
930 }
931
932 lldb::addr_t P = frame.Malloc(Tptr);
933
934 if (P == LLDB_INVALID_ADDRESS) {
935 LLDB_LOGF(log,
936 "Couldn't allocate the result pointer for an AllocaInst");
938 return false;
939 }
940
941 lldb_private::Status write_error;
942
943 execution_unit.WritePointerToMemory(P, R, write_error);
944
945 if (!write_error.Success()) {
946 LLDB_LOGF(log, "Couldn't write the result pointer for an AllocaInst");
948 lldb_private::Status free_error;
949 execution_unit.Free(P, free_error);
950 execution_unit.Free(R, free_error);
951 return false;
952 }
953
954 frame.m_values[alloca_inst] = P;
955
956 LLDB_LOGF(log, "Interpreted an AllocaInst");
957 LLDB_LOGF(log, " R : 0x%" PRIx64, R);
958 LLDB_LOGF(log, " P : 0x%" PRIx64, P);
959 } break;
960 case Instruction::BitCast:
961 case Instruction::ZExt: {
962 const CastInst *cast_inst = cast<CastInst>(inst);
963
964 Value *source = cast_inst->getOperand(0);
965
967
968 if (!frame.EvaluateValue(S, source, module)) {
969 LLDB_LOGF(log, "Couldn't evaluate %s", PrintValue(source).c_str());
971 return false;
972 }
973
974 frame.AssignValue(inst, S, module);
975 } break;
976 case Instruction::SExt: {
977 const CastInst *cast_inst = cast<CastInst>(inst);
978
979 Value *source = cast_inst->getOperand(0);
980
982
983 if (!frame.EvaluateValue(S, source, module)) {
984 LLDB_LOGF(log, "Couldn't evaluate %s", PrintValue(source).c_str());
986 return false;
987 }
988
989 S.MakeSigned();
990
991 lldb_private::Scalar S_signextend(S.SLongLong());
992
993 frame.AssignValue(inst, S_signextend, module);
994 } break;
995 case Instruction::UncondBr:
996 frame.Jump(cast<UncondBrInst>(inst)->getSuccessor());
997 LLDB_LOGF(log, "Interpreted an UncondBrInst");
998 continue;
999 case Instruction::CondBr: {
1000 const CondBrInst *br_inst = cast<CondBrInst>(inst);
1001
1002 Value *condition = br_inst->getCondition();
1003
1005
1006 if (!frame.EvaluateValue(C, condition, module)) {
1007 LLDB_LOGF(log, "Couldn't evaluate %s", PrintValue(condition).c_str());
1009 return false;
1010 }
1011
1012 if (!C.IsZero())
1013 frame.Jump(br_inst->getSuccessor(0));
1014 else
1015 frame.Jump(br_inst->getSuccessor(1));
1016
1017 LLDB_LOGF(log, "Interpreted a CondBrInst");
1018 LLDB_LOGF(log, " cond : %s", frame.SummarizeValue(condition).c_str());
1019 }
1020 continue;
1021 case Instruction::PHI: {
1022 const PHINode *phi_inst = cast<PHINode>(inst);
1023 if (!frame.m_prev_bb) {
1024 LLDB_LOGF(log,
1025 "Encountered PHI node without having jumped from another "
1026 "basic block");
1027 error =
1029 return false;
1030 }
1031
1032 Value *value = phi_inst->getIncomingValueForBlock(frame.m_prev_bb);
1033 lldb_private::Scalar result;
1034 if (!frame.EvaluateValue(result, value, module)) {
1035 LLDB_LOGF(log, "Couldn't evaluate %s", PrintValue(value).c_str());
1037 return false;
1038 }
1039 frame.AssignValue(inst, result, module);
1040
1041 LLDB_LOGF(log, "Interpreted a %s", inst->getOpcodeName());
1042 LLDB_LOGF(log, " Incoming value : %s",
1043 frame.SummarizeValue(value).c_str());
1044 } break;
1045 case Instruction::GetElementPtr: {
1046 const GetElementPtrInst *gep_inst = cast<GetElementPtrInst>(inst);
1047
1048 const Value *pointer_operand = gep_inst->getPointerOperand();
1049 Type *src_elem_ty = gep_inst->getSourceElementType();
1050
1052
1053 if (!frame.EvaluateValue(P, pointer_operand, module)) {
1054 LLDB_LOGF(log, "Couldn't evaluate %s",
1055 PrintValue(pointer_operand).c_str());
1057 return false;
1058 }
1059
1060 typedef SmallVector<Value *, 8> IndexVector;
1061 typedef IndexVector::iterator IndexIterator;
1062
1063 SmallVector<Value *, 8> indices(gep_inst->idx_begin(),
1064 gep_inst->idx_end());
1065
1066 SmallVector<Value *, 8> const_indices;
1067
1068 for (IndexIterator ii = indices.begin(), ie = indices.end(); ii != ie;
1069 ++ii) {
1070 ConstantInt *constant_index = dyn_cast<ConstantInt>(*ii);
1071
1072 if (!constant_index) {
1074
1075 if (!frame.EvaluateValue(I, *ii, module)) {
1076 LLDB_LOGF(log, "Couldn't evaluate %s", PrintValue(*ii).c_str());
1078 return false;
1079 }
1080
1081 LLDB_LOGF(log, "Evaluated constant index %s as %llu",
1082 PrintValue(*ii).c_str(), I.ULongLong(LLDB_INVALID_ADDRESS));
1083
1084 constant_index = cast<ConstantInt>(ConstantInt::get(
1085 (*ii)->getType(), I.ULongLong(LLDB_INVALID_ADDRESS)));
1086 }
1087
1088 const_indices.push_back(constant_index);
1089 }
1090
1091 uint64_t offset =
1092 data_layout.getIndexedOffsetInType(src_elem_ty, const_indices);
1093
1094 lldb_private::Scalar Poffset = P + offset;
1095
1096 frame.AssignValue(inst, Poffset, module);
1097
1098 LLDB_LOGF(log, "Interpreted a GetElementPtrInst");
1099 LLDB_LOGF(log, " P : %s",
1100 frame.SummarizeValue(pointer_operand).c_str());
1101 LLDB_LOGF(log, " Poffset : %s", frame.SummarizeValue(inst).c_str());
1102 } break;
1103 case Instruction::FCmp:
1104 case Instruction::ICmp: {
1105 const CmpInst *icmp_inst = cast<CmpInst>(inst);
1106
1107 CmpInst::Predicate predicate = icmp_inst->getPredicate();
1108
1109 Value *lhs = inst->getOperand(0);
1110 Value *rhs = inst->getOperand(1);
1111
1114
1115 if (!frame.EvaluateValue(L, lhs, module)) {
1116 LLDB_LOGF(log, "Couldn't evaluate %s", PrintValue(lhs).c_str());
1118 return false;
1119 }
1120
1121 if (!frame.EvaluateValue(R, rhs, module)) {
1122 LLDB_LOGF(log, "Couldn't evaluate %s", PrintValue(rhs).c_str());
1124 return false;
1125 }
1126
1127 lldb_private::Scalar result;
1128
1129 switch (predicate) {
1130 default:
1131 return false;
1132 case CmpInst::ICMP_EQ:
1133 case CmpInst::FCMP_OEQ:
1134 result = (L == R);
1135 break;
1136 case CmpInst::ICMP_NE:
1137 case CmpInst::FCMP_UNE:
1138 result = (L != R);
1139 break;
1140 case CmpInst::ICMP_UGT:
1141 L.MakeUnsigned();
1142 R.MakeUnsigned();
1143 result = (L > R);
1144 break;
1145 case CmpInst::ICMP_UGE:
1146 L.MakeUnsigned();
1147 R.MakeUnsigned();
1148 result = (L >= R);
1149 break;
1150 case CmpInst::FCMP_OGE:
1151 result = (L >= R);
1152 break;
1153 case CmpInst::FCMP_OGT:
1154 result = (L > R);
1155 break;
1156 case CmpInst::ICMP_ULT:
1157 L.MakeUnsigned();
1158 R.MakeUnsigned();
1159 result = (L < R);
1160 break;
1161 case CmpInst::FCMP_OLT:
1162 result = (L < R);
1163 break;
1164 case CmpInst::ICMP_ULE:
1165 L.MakeUnsigned();
1166 R.MakeUnsigned();
1167 result = (L <= R);
1168 break;
1169 case CmpInst::FCMP_OLE:
1170 result = (L <= R);
1171 break;
1172 case CmpInst::ICMP_SGT:
1173 L.MakeSigned();
1174 R.MakeSigned();
1175 result = (L > R);
1176 break;
1177 case CmpInst::ICMP_SGE:
1178 L.MakeSigned();
1179 R.MakeSigned();
1180 result = (L >= R);
1181 break;
1182 case CmpInst::ICMP_SLT:
1183 L.MakeSigned();
1184 R.MakeSigned();
1185 result = (L < R);
1186 break;
1187 case CmpInst::ICMP_SLE:
1188 L.MakeSigned();
1189 R.MakeSigned();
1190 result = (L <= R);
1191 break;
1192 }
1193
1194 frame.AssignValue(inst, result, module);
1195
1196 LLDB_LOGF(log, "Interpreted an ICmpInst");
1197 LLDB_LOGF(log, " L : %s", frame.SummarizeValue(lhs).c_str());
1198 LLDB_LOGF(log, " R : %s", frame.SummarizeValue(rhs).c_str());
1199 LLDB_LOGF(log, " = : %s", frame.SummarizeValue(inst).c_str());
1200 } break;
1201 case Instruction::IntToPtr: {
1202 const IntToPtrInst *int_to_ptr_inst = cast<IntToPtrInst>(inst);
1203
1204 Value *src_operand = int_to_ptr_inst->getOperand(0);
1205
1207
1208 if (!frame.EvaluateValue(I, src_operand, module)) {
1209 LLDB_LOGF(log, "Couldn't evaluate %s", PrintValue(src_operand).c_str());
1211 return false;
1212 }
1213
1214 frame.AssignValue(inst, I, module);
1215
1216 LLDB_LOGF(log, "Interpreted an IntToPtr");
1217 LLDB_LOGF(log, " Src : %s", frame.SummarizeValue(src_operand).c_str());
1218 LLDB_LOGF(log, " = : %s", frame.SummarizeValue(inst).c_str());
1219 } break;
1220 case Instruction::PtrToInt: {
1221 const PtrToIntInst *ptr_to_int_inst = cast<PtrToIntInst>(inst);
1222
1223 Value *src_operand = ptr_to_int_inst->getOperand(0);
1224
1226
1227 if (!frame.EvaluateValue(I, src_operand, module)) {
1228 LLDB_LOGF(log, "Couldn't evaluate %s", PrintValue(src_operand).c_str());
1230 return false;
1231 }
1232
1233 frame.AssignValue(inst, I, module);
1234
1235 LLDB_LOGF(log, "Interpreted a PtrToInt");
1236 LLDB_LOGF(log, " Src : %s", frame.SummarizeValue(src_operand).c_str());
1237 LLDB_LOGF(log, " = : %s", frame.SummarizeValue(inst).c_str());
1238 } break;
1239 case Instruction::Trunc: {
1240 const TruncInst *trunc_inst = cast<TruncInst>(inst);
1241
1242 Value *src_operand = trunc_inst->getOperand(0);
1243
1245
1246 if (!frame.EvaluateValue(I, src_operand, module)) {
1247 LLDB_LOGF(log, "Couldn't evaluate %s", PrintValue(src_operand).c_str());
1249 return false;
1250 }
1251
1252 frame.AssignValue(inst, I, module);
1253
1254 LLDB_LOGF(log, "Interpreted a Trunc");
1255 LLDB_LOGF(log, " Src : %s", frame.SummarizeValue(src_operand).c_str());
1256 LLDB_LOGF(log, " = : %s", frame.SummarizeValue(inst).c_str());
1257 } break;
1258 case Instruction::FPToUI:
1259 case Instruction::FPToSI: {
1260 Value *src_operand = inst->getOperand(0);
1261
1263 if (!frame.EvaluateValue(S, src_operand, module)) {
1264 LLDB_LOGF(log, "Couldn't evaluate %s", PrintValue(src_operand).c_str());
1266 return false;
1267 }
1268
1269 assert(inst->getType()->isIntegerTy() && "Unexpected target type");
1270 llvm::APSInt result(inst->getType()->getIntegerBitWidth(),
1271 /*isUnsigned=*/inst->getOpcode() ==
1272 Instruction::FPToUI);
1273 assert(S.GetType() == lldb_private::Scalar::e_float &&
1274 "Unexpected source type");
1275 bool isExact;
1276 llvm::APFloatBase::opStatus status = S.GetAPFloat().convertToInteger(
1277 result, llvm::APFloat::rmTowardZero, &isExact);
1278 // Casting floating point values that are out of bounds of the target type
1279 // is undefined behaviour.
1280 if (status & llvm::APFloatBase::opInvalidOp) {
1281 std::string s;
1282 raw_string_ostream rso(s);
1283 rso << "Conversion error: " << S << " cannot be converted to ";
1284 if (inst->getOpcode() == Instruction::FPToUI)
1285 rso << "unsigned ";
1286 rso << *inst->getType();
1287 LLDB_LOGF(log, "%s", s.c_str());
1289 return false;
1290 }
1291 lldb_private::Scalar R(result);
1292
1293 frame.AssignValue(inst, R, module);
1294 LLDB_LOGF(log, "Interpreted a %s", inst->getOpcodeName());
1295 LLDB_LOGF(log, " Src : %s", frame.SummarizeValue(src_operand).c_str());
1296 LLDB_LOGF(log, " = : %s", frame.SummarizeValue(inst).c_str());
1297 } break;
1298 case Instruction::UIToFP:
1299 case Instruction::SIToFP:
1300 case Instruction::FPTrunc:
1301 case Instruction::FPExt: {
1302 Value *src_operand = inst->getOperand(0);
1303
1305 if (!frame.EvaluateValue(S, src_operand, module)) {
1306 LLDB_LOGF(log, "Couldn't evaluate %s", PrintValue(src_operand).c_str());
1308 return false;
1309 }
1311
1312 Type *result_type = inst->getType();
1313 assert(
1314 (result_type->isFloatTy() || result_type->isDoubleTy()) &&
1315 "Unsupported result type; CanInterpret() should have checked that");
1316 if (result_type->isFloatTy())
1317 R = S.Float();
1318 else
1319 R = S.Double();
1320
1321 frame.AssignValue(inst, R, module);
1322 LLDB_LOGF(log, "Interpreted a %s", inst->getOpcodeName());
1323 LLDB_LOGF(log, " Src : %s", frame.SummarizeValue(src_operand).c_str());
1324 LLDB_LOGF(log, " = : %s", frame.SummarizeValue(inst).c_str());
1325 } break;
1326 case Instruction::Load: {
1327 const LoadInst *load_inst = cast<LoadInst>(inst);
1328
1329 // The semantics of Load are:
1330 // Create a region D that will contain the loaded data
1331 // Resolve the region P containing a pointer
1332 // Dereference P to get the region R that the data should be loaded from
1333 // Transfer a unit of type type(D) from R to D
1334
1335 const Value *pointer_operand = load_inst->getPointerOperand();
1336
1337 lldb::addr_t D = frame.ResolveValue(load_inst, module);
1338 lldb::addr_t P = frame.ResolveValue(pointer_operand, module);
1339
1340 if (D == LLDB_INVALID_ADDRESS) {
1341 LLDB_LOGF(log, "LoadInst's value doesn't resolve to anything");
1343 return false;
1344 }
1345
1346 if (P == LLDB_INVALID_ADDRESS) {
1347 LLDB_LOGF(log, "LoadInst's pointer doesn't resolve to anything");
1349 return false;
1350 }
1351
1352 lldb::addr_t R;
1353 lldb_private::Status read_error;
1354 execution_unit.ReadPointerFromMemory(&R, P, read_error);
1355
1356 if (!read_error.Success()) {
1357 LLDB_LOGF(log, "Couldn't read the address to be loaded for a LoadInst");
1359 return false;
1360 }
1361
1362 Type *target_ty = load_inst->getType();
1363 size_t target_size = data_layout.getTypeStoreSize(target_ty);
1364 lldb_private::DataBufferHeap buffer(target_size, 0);
1365
1366 read_error.Clear();
1367 execution_unit.ReadMemory(buffer.GetBytes(), R, buffer.GetByteSize(),
1368 read_error);
1369 if (!read_error.Success()) {
1370 LLDB_LOGF(log, "Couldn't read from a region on behalf of a LoadInst");
1372 return false;
1373 }
1374
1375 lldb_private::Status write_error;
1376 execution_unit.WriteMemory(D, buffer.GetBytes(), buffer.GetByteSize(),
1377 write_error);
1378 if (!write_error.Success()) {
1379 LLDB_LOGF(log, "Couldn't write to a region on behalf of a LoadInst");
1381 return false;
1382 }
1383
1384 LLDB_LOGF(log, "Interpreted a LoadInst");
1385 LLDB_LOGF(log, " P : 0x%" PRIx64, P);
1386 LLDB_LOGF(log, " R : 0x%" PRIx64, R);
1387 LLDB_LOGF(log, " D : 0x%" PRIx64, D);
1388 } break;
1389 case Instruction::Ret: {
1390 return true;
1391 }
1392 case Instruction::Store: {
1393 const StoreInst *store_inst = cast<StoreInst>(inst);
1394
1395 // The semantics of Store are:
1396 // Resolve the region D containing the data to be stored
1397 // Resolve the region P containing a pointer
1398 // Dereference P to get the region R that the data should be stored in
1399 // Transfer a unit of type type(D) from D to R
1400
1401 const Value *value_operand = store_inst->getValueOperand();
1402 const Value *pointer_operand = store_inst->getPointerOperand();
1403
1404 lldb::addr_t D = frame.ResolveValue(value_operand, module);
1405 lldb::addr_t P = frame.ResolveValue(pointer_operand, module);
1406
1407 if (D == LLDB_INVALID_ADDRESS) {
1408 LLDB_LOGF(log, "StoreInst's value doesn't resolve to anything");
1410 return false;
1411 }
1412
1413 if (P == LLDB_INVALID_ADDRESS) {
1414 LLDB_LOGF(log, "StoreInst's pointer doesn't resolve to anything");
1416 return false;
1417 }
1418
1419 lldb::addr_t R;
1420 lldb_private::Status read_error;
1421 execution_unit.ReadPointerFromMemory(&R, P, read_error);
1422
1423 if (!read_error.Success()) {
1424 LLDB_LOGF(log, "Couldn't read the address to be loaded for a LoadInst");
1426 return false;
1427 }
1428
1429 Type *target_ty = value_operand->getType();
1430 size_t target_size = data_layout.getTypeStoreSize(target_ty);
1431 lldb_private::DataBufferHeap buffer(target_size, 0);
1432
1433 read_error.Clear();
1434 execution_unit.ReadMemory(buffer.GetBytes(), D, buffer.GetByteSize(),
1435 read_error);
1436 if (!read_error.Success()) {
1437 LLDB_LOGF(log, "Couldn't read from a region on behalf of a StoreInst");
1439 return false;
1440 }
1441
1442 lldb_private::Status write_error;
1443 execution_unit.WriteMemory(R, buffer.GetBytes(), buffer.GetByteSize(),
1444 write_error);
1445 if (!write_error.Success()) {
1446 LLDB_LOGF(log, "Couldn't write to a region on behalf of a StoreInst");
1448 return false;
1449 }
1450
1451 LLDB_LOGF(log, "Interpreted a StoreInst");
1452 LLDB_LOGF(log, " D : 0x%" PRIx64, D);
1453 LLDB_LOGF(log, " P : 0x%" PRIx64, P);
1454 LLDB_LOGF(log, " R : 0x%" PRIx64, R);
1455 } break;
1456 case Instruction::Call: {
1457 const CallInst *call_inst = cast<CallInst>(inst);
1458
1459 if (auto *fn = call_inst->getCalledFunction()) {
1460 if (fn->isIntrinsic() &&
1461 ((fn->getIntrinsicID() == llvm::Intrinsic::ptrauth_auth &&
1462 call_inst->arg_size() == 3) ||
1463 (fn->getIntrinsicID() == llvm::Intrinsic::ptrauth_strip &&
1464 call_inst->arg_size() == 2)) &&
1465 exe_ctx.GetProcessPtr()) {
1466 llvm::Value *auth_ptr = call_inst->getArgOperand(0);
1467 // Extract the argument's value.
1468 lldb_private::Scalar auth_ptr_val;
1469 if (!frame.EvaluateValue(auth_ptr_val, auth_ptr, module)) {
1471 "unable to evaluate argument 0");
1472 return false;
1473 }
1474
1475 if (lldb::ABISP abi_sp = exe_ctx.GetProcessPtr()->GetABI()) {
1476 auto stripped_ptr = lldb_private::Scalar(
1477 abi_sp->FixCodeAddress(auth_ptr_val.ULongLong()));
1478 frame.AssignValue(call_inst, stripped_ptr, module);
1479 }
1480 }
1481
1482 if (fn->isIntrinsic() &&
1483 fn->getIntrinsicID() == llvm::Intrinsic::ptrauth_blend) {
1484 llvm::Value *addr = call_inst->getArgOperand(0);
1485 llvm::Value *lobits = call_inst->getArgOperand(1);
1486
1487 // Extract the address.
1488 lldb_private::Scalar addr_val;
1489 if (!frame.EvaluateValue(addr_val, addr, module)) {
1491 "unable to evaluate argument %d", 0);
1492 return false;
1493 }
1494
1495 // Extract the low bits to blend in.
1496 lldb_private::Scalar lobits_val;
1497 if (!frame.EvaluateValue(lobits_val, lobits, module)) {
1499 "unable to evaluate argument %d", 1);
1500 return false;
1501 }
1502
1503 lldb_private::Scalar blend_val = addr_val | (lobits_val << 48);
1504 frame.AssignValue(call_inst, blend_val, module);
1505 }
1506 }
1507
1508 if (CanIgnoreCall(call_inst))
1509 break;
1510
1511 // Get the return type
1512 llvm::Type *returnType = call_inst->getType();
1513 if (returnType == nullptr) {
1515 "unable to access return type");
1516 return false;
1517 }
1518
1519 // Work with void, integer and pointer return types
1520 if (!returnType->isVoidTy() && !returnType->isIntegerTy() &&
1521 !returnType->isPointerTy()) {
1523 "return type is not supported");
1524 return false;
1525 }
1526
1527 // Check we can actually get a thread
1528 if (exe_ctx.GetThreadPtr() == nullptr) {
1529 error =
1530 lldb_private::Status::FromErrorString("unable to acquire thread");
1531 return false;
1532 }
1533
1534 // Make sure we have a valid process
1535 if (!process) {
1536 error =
1537 lldb_private::Status::FromErrorString("unable to get the process");
1538 return false;
1539 }
1540
1541 // Find the address of the callee function
1543 const llvm::Value *val = call_inst->getCalledOperand();
1544
1545 if (!frame.EvaluateValue(I, val, module)) {
1547 "unable to get address of function");
1548 return false;
1549 }
1551
1554
1555 llvm::FunctionType *prototype = call_inst->getFunctionType();
1556
1557 // Find number of arguments
1558 const int numArgs = call_inst->arg_size();
1559
1560 // We work with a fixed array of 16 arguments which is our upper limit
1561 static lldb_private::ABI::CallArgument rawArgs[16];
1562 if (numArgs >= 16) {
1564 "function takes too many arguments");
1565 return false;
1566 }
1567
1568 // Push all function arguments to the argument list that will be passed
1569 // to the call function thread plan
1570 for (int i = 0; i < numArgs; i++) {
1571 // Get details of this argument
1572 llvm::Value *arg_op = call_inst->getArgOperand(i);
1573 llvm::Type *arg_ty = arg_op->getType();
1574
1575 // Ensure that this argument is an supported type
1576 if (!arg_ty->isIntegerTy() && !arg_ty->isPointerTy()) {
1578 "argument %d must be integer type", i);
1579 return false;
1580 }
1581
1582 // Extract the arguments value
1583 lldb_private::Scalar tmp_op = 0;
1584 if (!frame.EvaluateValue(tmp_op, arg_op, module)) {
1586 "unable to evaluate argument %d", i);
1587 return false;
1588 }
1589
1590 // Check if this is a string literal or constant string pointer
1591 if (arg_ty->isPointerTy()) {
1592 lldb::addr_t addr = tmp_op.ULongLong();
1593 size_t dataSize = 0;
1594
1595 bool Success = execution_unit.GetAllocSize(addr, dataSize);
1597 assert(Success &&
1598 "unable to locate host data for transfer to device");
1599 // Create the required buffer
1600 rawArgs[i].size = dataSize;
1601 rawArgs[i].data_up.reset(new uint8_t[dataSize + 1]);
1602
1603 // Read string from host memory
1604 execution_unit.ReadMemory(rawArgs[i].data_up.get(), addr, dataSize,
1605 error);
1606 assert(!error.Fail() &&
1607 "we have failed to read the string from memory");
1608
1609 // Add null terminator
1610 rawArgs[i].data_up[dataSize] = '\0';
1612 } else /* if ( arg_ty->isPointerTy() ) */
1613 {
1615 // Get argument size in bytes
1616 rawArgs[i].size = arg_ty->getIntegerBitWidth() / 8;
1617 // Push value into argument list for thread plan
1618 rawArgs[i].value = tmp_op.ULongLong();
1619 }
1620 }
1621
1622 // Pack the arguments into an llvm::array
1623 llvm::ArrayRef<lldb_private::ABI::CallArgument> args(rawArgs, numArgs);
1624
1625 // Setup a thread plan to call the target function
1626 lldb::ThreadPlanSP call_plan_sp(
1628 exe_ctx.GetThreadRef(), funcAddr, *prototype, *returnType, args,
1629 options));
1630
1631 // Check if the plan is valid
1633 if (!call_plan_sp || !call_plan_sp->ValidatePlan(&ss)) {
1635 "unable to make ThreadPlanCallFunctionUsingABI for 0x%llx",
1636 I.ULongLong());
1637 return false;
1638 }
1639
1640 process->SetRunningUserExpression(true);
1641
1642 lldb_private::PolicyStack::Guard expr_policy_guard =
1644
1645 // Execute the actual function call thread plan
1647 process->RunThreadPlan(exe_ctx, call_plan_sp, options, diagnostics);
1648
1649 // Check that the thread plan completed successfully
1652 "ThreadPlanCallFunctionUsingABI failed");
1653 return false;
1654 }
1655
1656 process->SetRunningUserExpression(false);
1657
1658 // Void return type
1659 if (returnType->isVoidTy()) {
1660 // Cant assign to void types, so we leave the frame untouched
1661 } else
1662 // Integer or pointer return type
1663 if (returnType->isIntegerTy() || returnType->isPointerTy()) {
1664 // Get the encapsulated return value
1665 lldb::ValueObjectSP retVal = call_plan_sp.get()->GetReturnValueObject();
1666
1667 lldb_private::Scalar returnVal = -1;
1668 lldb_private::ValueObject *vobj = retVal.get();
1669
1670 // Check if the return value is valid
1671 if (vobj == nullptr || !retVal) {
1673 "unable to get the return value");
1674 return false;
1675 }
1676
1677 // Extract the return value as a integer
1678 lldb_private::Value &value = vobj->GetValue();
1679 returnVal = value.GetScalar();
1680
1681 // Push the return value as the result
1682 frame.AssignValue(inst, returnVal, module);
1683 }
1684 } break;
1685 }
1686
1687 ++frame.m_ii;
1688 }
1689
1690 return false;
1691}
static llvm::raw_ostream & error(Stream &strm)
#define INTERRUPT_REQUESTED(debugger,...)
This handy define will keep you from having to generate a report for the interruption by hand.
Definition Debugger.h:525
static bool CanResolveConstant(llvm::Constant *constant)
static const char * memory_allocation_error
static const char * memory_read_error
static std::string PrintValue(const Value *value, bool truncate=false)
static const char * interpreter_internal_error
static std::string PrintType(const Type *type, bool truncate=false)
static const char * interrupt_error
static const char * unsupported_operand_error
static const char * timeout_error
static bool CanIgnoreCall(const CallInst *call)
static const char * memory_write_error
static const char * unsupported_opcode_error
static const char * bad_value_error
static const char * too_many_functions_error
#define LLDB_LOGF(log,...)
Definition Log.h:389
static bool CanInterpret(llvm::Module &module, llvm::Function &function, lldb_private::Status &error, const bool support_function_calls)
static bool Interpret(llvm::Module &module, llvm::Function &function, llvm::ArrayRef< lldb::addr_t > args, lldb_private::IRExecutionUnit &execution_unit, lldb_private::Status &error, lldb::addr_t stack_frame_bottom, lldb::addr_t stack_frame_top, lldb_private::ExecutionContext &exe_ctx, lldb_private::Timeout< std::micro > timeout)
lldb::addr_t ResolveValue(const Value *value, Module &module)
const BasicBlock * m_bb
std::string SummarizeValue(const Value *value)
bool ResolveConstantValue(APInt &value, const Constant *constant)
bool ResolveConstant(lldb::addr_t process_address, const Constant *constant)
const DataLayout & m_target_data
lldb_private::IRExecutionUnit & m_execution_unit
bool MakeArgument(const Argument *value, uint64_t address)
lldb::addr_t Malloc(size_t size, uint8_t byte_alignment)
const BasicBlock * m_prev_bb
BasicBlock::const_iterator m_ie
lldb::addr_t Malloc(llvm::Type *type)
bool AssignToMatchType(lldb_private::Scalar &scalar, llvm::APInt value, Type *type)
~InterpreterStackFrame()=default
InterpreterStackFrame(const DataLayout &target_data, lldb_private::IRExecutionUnit &execution_unit, lldb::addr_t stack_frame_bottom, lldb::addr_t stack_frame_top)
void Jump(const BasicBlock *bb)
std::string PrintData(lldb::addr_t addr, llvm::Type *type)
std::map< const Value *, lldb::addr_t > ValueMap
BasicBlock::const_iterator m_ii
lldb::ByteOrder m_byte_order
bool EvaluateValue(lldb_private::Scalar &scalar, const Value *value, Module &module)
bool AssignValue(const Value *value, lldb_private::Scalar scalar, Module &module)
lldb::addr_t m_frame_process_address
A section + offset based address class.
Definition Address.h:62
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.
float GetFloat(lldb::offset_t *offset_ptr) const
Extract a float from *offset_ptr.
uint64_t GetMaxU64(lldb::offset_t *offset_ptr, size_t byte_size) const
Extract an unsigned integer of size byte_size from *offset_ptr.
double GetDouble(lldb::offset_t *offset_ptr) const
"lldb/Target/ExecutionContext.h" A class that contains an execution context.
Target * GetTargetPtr() const
Returns a pointer to the target object.
Process * GetProcessPtr() const
Returns a pointer to the process object.
Thread & GetThreadRef() const
Returns a reference to the thread object.
Thread * GetThreadPtr() const
Returns a pointer to the thread object.
"lldb/Expression/IRExecutionUnit.h" Contains the IR and, optionally, JIT- compiled code for a module.
void Free(lldb::addr_t process_address, Status &error)
void ReadPointerFromMemory(lldb::addr_t *address, lldb::addr_t process_address, Status &error)
void WritePointerToMemory(lldb::addr_t process_address, lldb::addr_t pointer, Status &error)
bool GetAllocSize(lldb::addr_t address, size_t &size)
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)
RAII guard that pops a policy on destruction.
Definition Policy.h:112
Guard PushPublicStateRunningExpression()
Definition Policy.h:140
static PolicyStack & Get()
Definition Policy.cpp:21
A plug-in interface definition class for debugging a process.
Definition Process.h:369
lldb::ExpressionResults RunThreadPlan(ExecutionContext &exe_ctx, lldb::ThreadPlanSP &thread_plan_sp, const EvaluateExpressionOptions &requested_options, DiagnosticManager &diagnostic_manager)
Definition Process.cpp:5260
void SetRunningUserExpression(bool on)
Definition Process.cpp:1519
const lldb::ABISP & GetABI()
Definition Process.cpp:1529
bool IsZero() const
Definition Scalar.cpp:175
unsigned long long ULongLong(unsigned long long fail_value=0) const
Definition Scalar.cpp:366
size_t GetAsMemoryData(void *dst, size_t dst_len, lldb::ByteOrder dst_byte_order, Status &error) const
Definition Scalar.cpp:791
float Float(float fail_value=0.0f) const
Definition Scalar.cpp:394
double Double(double fail_value=0.0) const
Definition Scalar.cpp:414
bool ShiftRightLogical(const Scalar &rhs)
Definition Scalar.cpp:465
llvm::APInt UInt128(const llvm::APInt &fail_value) const
Definition Scalar.cpp:382
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
bool Success() const
Test for success condition.
Definition Status.cpp:303
llvm::StringRef GetString() const
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
Definition Stream.cpp:134
size_t PutCString(llvm::StringRef cstr)
Output a C string to the stream.
Definition Stream.cpp:63
Debugger & GetDebugger() const
Definition Target.h:1365
const Value & GetValue() const
const Scalar & GetScalar() const
See comment on m_scalar to understand what GetScalar returns.
Definition Value.h:114
uint8_t * GetBytes()
Get a pointer to the data.
Definition DataBuffer.h:108
#define UNUSED_IF_ASSERT_DISABLED(x)
#define LLDB_INVALID_ADDRESS
std::shared_ptr< lldb_private::ThreadPlan > ThreadPlanSP
std::shared_ptr< lldb_private::ABI > ABISP
std::shared_ptr< lldb_private::ValueObject > ValueObjectSP
uint64_t offset_t
Definition lldb-types.h:86
ExpressionResults
The results of expression evaluation.
@ eExpressionCompleted
ByteOrder
Byte ordering definitions.
uint64_t addr_t
Definition lldb-types.h:80
std::unique_ptr< uint8_t[]> data_up
Definition ABI.h:39