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