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