blob: 5acb2e9144272a1a4532153d3a82ce5a77335707 [file] [log] [blame]
Sean Callanan3bfdaa22011-09-15 02:13:07 +00001//===-- IRInterpreter.cpp ---------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Sean Callanan579e70c2016-03-19 00:03:59 +000010#include "lldb/Expression/IRInterpreter.h"
Ewan Crawford90ff7912015-07-14 10:56:58 +000011#include "lldb/Core/Module.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000012#include "lldb/Core/ModuleSpec.h"
Ewan Crawford90ff7912015-07-14 10:56:58 +000013#include "lldb/Core/ValueObject.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000014#include "lldb/Expression/DiagnosticManager.h"
Ted Woodward7071c5fd2016-03-01 21:53:26 +000015#include "lldb/Expression/IRExecutionUnit.h"
Sean Callananfefe43c2013-04-25 18:55:45 +000016#include "lldb/Expression/IRMemoryMap.h"
Zachary Turnerbf9a7732017-02-02 21:39:50 +000017#include "lldb/Utility/ConstString.h"
Zachary Turner666cc0b2017-03-04 01:30:05 +000018#include "lldb/Utility/DataExtractor.h"
Zachary Turner01c32432017-02-14 19:06:07 +000019#include "lldb/Utility/Endian.h"
Zachary Turner6f9e6902017-03-03 20:56:28 +000020#include "lldb/Utility/Log.h"
Pavel Labathd821c992018-08-07 11:07:21 +000021#include "lldb/Utility/Scalar.h"
Zachary Turner97206d52017-05-12 04:51:55 +000022#include "lldb/Utility/Status.h"
Zachary Turnerbf9a7732017-02-02 21:39:50 +000023#include "lldb/Utility/StreamString.h"
Sean Callanan3bfdaa22011-09-15 02:13:07 +000024
Ewan Crawford90ff7912015-07-14 10:56:58 +000025#include "lldb/Target/ABI.h"
26#include "lldb/Target/ExecutionContext.h"
27#include "lldb/Target/Target.h"
28#include "lldb/Target/Thread.h"
29#include "lldb/Target/ThreadPlan.h"
30#include "lldb/Target/ThreadPlanCallFunctionUsingABI.h"
31
Chandler Carruth1e157582013-01-02 12:20:07 +000032#include "llvm/IR/Constants.h"
Sean Callananfefe43c2013-04-25 18:55:45 +000033#include "llvm/IR/DataLayout.h"
Chandler Carruth1e157582013-01-02 12:20:07 +000034#include "llvm/IR/Function.h"
35#include "llvm/IR/Instructions.h"
Sean Callanan576a4372014-03-25 19:33:15 +000036#include "llvm/IR/Intrinsics.h"
Ewan Crawford90ff7912015-07-14 10:56:58 +000037#include "llvm/IR/LLVMContext.h"
Chandler Carruth1e157582013-01-02 12:20:07 +000038#include "llvm/IR/Module.h"
Eduard Burtescud05b8992016-01-22 03:43:23 +000039#include "llvm/IR/Operator.h"
Sean Callanan3bfdaa22011-09-15 02:13:07 +000040#include "llvm/Support/raw_ostream.h"
Sean Callanan3bfdaa22011-09-15 02:13:07 +000041
42#include <map>
43
44using namespace llvm;
45
Kate Stoneb9c1b512016-09-06 20:57:50 +000046static std::string PrintValue(const Value *value, bool truncate = false) {
47 std::string s;
48 raw_string_ostream rso(s);
49 value->print(rso);
50 rso.flush();
51 if (truncate)
52 s.resize(s.length() - 1);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +000053
Kate Stoneb9c1b512016-09-06 20:57:50 +000054 size_t offset;
55 while ((offset = s.find('\n')) != s.npos)
56 s.erase(offset, 1);
57 while (s[0] == ' ' || s[0] == '\t')
58 s.erase(0, 1);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +000059
Kate Stoneb9c1b512016-09-06 20:57:50 +000060 return s;
Sean Callanan3bfdaa22011-09-15 02:13:07 +000061}
62
Kate Stoneb9c1b512016-09-06 20:57:50 +000063static std::string PrintType(const Type *type, bool truncate = false) {
64 std::string s;
65 raw_string_ostream rso(s);
66 type->print(rso);
67 rso.flush();
68 if (truncate)
69 s.resize(s.length() - 1);
70 return s;
Sean Callanan3bfdaa22011-09-15 02:13:07 +000071}
72
Kate Stoneb9c1b512016-09-06 20:57:50 +000073static bool CanIgnoreCall(const CallInst *call) {
74 const llvm::Function *called_function = call->getCalledFunction();
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +000075
Kate Stoneb9c1b512016-09-06 20:57:50 +000076 if (!called_function)
Sean Callanan576a4372014-03-25 19:33:15 +000077 return false;
Sean Callanan576a4372014-03-25 19:33:15 +000078
Kate Stoneb9c1b512016-09-06 20:57:50 +000079 if (called_function->isIntrinsic()) {
80 switch (called_function->getIntrinsicID()) {
Sean Callanan8c62daf2016-02-12 21:16:58 +000081 default:
Kate Stoneb9c1b512016-09-06 20:57:50 +000082 break;
83 case llvm::Intrinsic::dbg_declare:
84 case llvm::Intrinsic::dbg_value:
85 return true;
Sean Callanan8c62daf2016-02-12 21:16:58 +000086 }
Kate Stoneb9c1b512016-09-06 20:57:50 +000087 }
88
89 return false;
Sean Callanan8c62daf2016-02-12 21:16:58 +000090}
91
Kate Stoneb9c1b512016-09-06 20:57:50 +000092class InterpreterStackFrame {
93public:
94 typedef std::map<const Value *, lldb::addr_t> ValueMap;
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +000095
Kate Stoneb9c1b512016-09-06 20:57:50 +000096 ValueMap m_values;
97 DataLayout &m_target_data;
98 lldb_private::IRExecutionUnit &m_execution_unit;
99 const BasicBlock *m_bb;
100 const BasicBlock *m_prev_bb;
101 BasicBlock::const_iterator m_ii;
102 BasicBlock::const_iterator m_ie;
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000103
Kate Stoneb9c1b512016-09-06 20:57:50 +0000104 lldb::addr_t m_frame_process_address;
105 size_t m_frame_size;
106 lldb::addr_t m_stack_pointer;
107
108 lldb::ByteOrder m_byte_order;
109 size_t m_addr_byte_size;
110
111 InterpreterStackFrame(DataLayout &target_data,
112 lldb_private::IRExecutionUnit &execution_unit,
113 lldb::addr_t stack_frame_bottom,
114 lldb::addr_t stack_frame_top)
115 : m_target_data(target_data), m_execution_unit(execution_unit),
116 m_bb(nullptr), m_prev_bb(nullptr) {
117 m_byte_order = (target_data.isLittleEndian() ? lldb::eByteOrderLittle
118 : lldb::eByteOrderBig);
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() {}
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) {
136 lldb_private::StreamString ss;
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);
Sean Callanan85fc8762013-06-27 01:59:51 +0000146 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000147
Kate Stoneb9c1b512016-09-06 20:57:50 +0000148 return ss.GetString();
149 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000150
Kate Stoneb9c1b512016-09-06 20:57:50 +0000151 bool AssignToMatchType(lldb_private::Scalar &scalar, uint64_t u64value,
152 Type *type) {
153 size_t type_size = m_target_data.getTypeStoreSize(type);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000154
Kate Stoneb9c1b512016-09-06 20:57:50 +0000155 switch (type_size) {
156 case 1:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000157 case 2:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000158 case 4:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000159 case 8:
Pavel Labathc7c9d762018-06-20 10:45:29 +0000160 scalar = llvm::APInt(type_size*8, u64value);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000161 break;
162 default:
163 return false;
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000164 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000165
Adrian McCarthy3f998102016-05-04 23:32:35 +0000166 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000167 }
Sean Callanan14cb2aa2013-04-17 18:35:47 +0000168
Kate Stoneb9c1b512016-09-06 20:57:50 +0000169 bool EvaluateValue(lldb_private::Scalar &scalar, const Value *value,
170 Module &module) {
171 const Constant *constant = dyn_cast<Constant>(value);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000172
Kate Stoneb9c1b512016-09-06 20:57:50 +0000173 if (constant) {
174 APInt value_apint;
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000175
Kate Stoneb9c1b512016-09-06 20:57:50 +0000176 if (!ResolveConstantValue(value_apint, constant))
Sean Callanan14cb2aa2013-04-17 18:35:47 +0000177 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000178
179 return AssignToMatchType(scalar, value_apint.getLimitedValue(),
180 value->getType());
181 } else {
182 lldb::addr_t process_address = ResolveValue(value, module);
183 size_t value_size = m_target_data.getTypeStoreSize(value->getType());
184
185 lldb_private::DataExtractor value_extractor;
Zachary Turner97206d52017-05-12 04:51:55 +0000186 lldb_private::Status extract_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000187
188 m_execution_unit.GetMemoryData(value_extractor, process_address,
189 value_size, extract_error);
190
191 if (!extract_error.Success())
192 return false;
193
194 lldb::offset_t offset = 0;
195 if (value_size == 1 || value_size == 2 || value_size == 4 ||
196 value_size == 8) {
197 uint64_t u64value = value_extractor.GetMaxU64(&offset, value_size);
198 return AssignToMatchType(scalar, u64value, value->getType());
199 }
Sean Callanan14cb2aa2013-04-17 18:35:47 +0000200 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000201
Sean Callanan14cb2aa2013-04-17 18:35:47 +0000202 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000203 }
204
205 bool AssignValue(const Value *value, lldb_private::Scalar &scalar,
206 Module &module) {
207 lldb::addr_t process_address = ResolveValue(value, module);
208
209 if (process_address == LLDB_INVALID_ADDRESS)
210 return false;
211
212 lldb_private::Scalar cast_scalar;
213
214 if (!AssignToMatchType(cast_scalar, scalar.ULongLong(), value->getType()))
215 return false;
216
217 size_t value_byte_size = m_target_data.getTypeStoreSize(value->getType());
218
219 lldb_private::DataBufferHeap buf(value_byte_size, 0);
220
Zachary Turner97206d52017-05-12 04:51:55 +0000221 lldb_private::Status get_data_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000222
223 if (!cast_scalar.GetAsMemoryData(buf.GetBytes(), buf.GetByteSize(),
224 m_byte_order, get_data_error))
225 return false;
226
Zachary Turner97206d52017-05-12 04:51:55 +0000227 lldb_private::Status write_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000228
229 m_execution_unit.WriteMemory(process_address, buf.GetBytes(),
230 buf.GetByteSize(), write_error);
231
232 return write_error.Success();
233 }
234
235 bool ResolveConstantValue(APInt &value, const Constant *constant) {
236 switch (constant->getValueID()) {
237 default:
238 break;
239 case Value::FunctionVal:
240 if (const Function *constant_func = dyn_cast<Function>(constant)) {
241 lldb_private::ConstString name(constant_func->getName());
242 lldb::addr_t addr = m_execution_unit.FindSymbol(name);
243 if (addr == LLDB_INVALID_ADDRESS)
244 return false;
245 value = APInt(m_target_data.getPointerSizeInBits(), addr);
246 return true;
247 }
248 break;
249 case Value::ConstantIntVal:
250 if (const ConstantInt *constant_int = dyn_cast<ConstantInt>(constant)) {
251 value = constant_int->getValue();
252 return true;
253 }
254 break;
255 case Value::ConstantFPVal:
256 if (const ConstantFP *constant_fp = dyn_cast<ConstantFP>(constant)) {
257 value = constant_fp->getValueAPF().bitcastToAPInt();
258 return true;
259 }
260 break;
261 case Value::ConstantExprVal:
262 if (const ConstantExpr *constant_expr =
263 dyn_cast<ConstantExpr>(constant)) {
264 switch (constant_expr->getOpcode()) {
265 default:
266 return false;
267 case Instruction::IntToPtr:
268 case Instruction::PtrToInt:
269 case Instruction::BitCast:
270 return ResolveConstantValue(value, constant_expr->getOperand(0));
271 case Instruction::GetElementPtr: {
272 ConstantExpr::const_op_iterator op_cursor = constant_expr->op_begin();
273 ConstantExpr::const_op_iterator op_end = constant_expr->op_end();
274
275 Constant *base = dyn_cast<Constant>(*op_cursor);
276
277 if (!base)
278 return false;
279
280 if (!ResolveConstantValue(value, base))
281 return false;
282
283 op_cursor++;
284
285 if (op_cursor == op_end)
286 return true; // no offset to apply!
287
288 SmallVector<Value *, 8> indices(op_cursor, op_end);
289
290 Type *src_elem_ty =
291 cast<GEPOperator>(constant_expr)->getSourceElementType();
292 uint64_t offset =
293 m_target_data.getIndexedOffsetInType(src_elem_ty, indices);
294
295 const bool is_signed = true;
296 value += APInt(value.getBitWidth(), offset, is_signed);
297
298 return true;
299 }
300 }
301 }
302 break;
303 case Value::ConstantPointerNullVal:
304 if (isa<ConstantPointerNull>(constant)) {
305 value = APInt(m_target_data.getPointerSizeInBits(), 0);
306 return true;
307 }
308 break;
309 }
310 return false;
311 }
312
313 bool MakeArgument(const Argument *value, uint64_t address) {
314 lldb::addr_t data_address = Malloc(value->getType());
315
316 if (data_address == LLDB_INVALID_ADDRESS)
317 return false;
318
Zachary Turner97206d52017-05-12 04:51:55 +0000319 lldb_private::Status write_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000320
321 m_execution_unit.WritePointerToMemory(data_address, address, write_error);
322
323 if (!write_error.Success()) {
Zachary Turner97206d52017-05-12 04:51:55 +0000324 lldb_private::Status free_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000325 m_execution_unit.Free(data_address, free_error);
326 return false;
327 }
328
329 m_values[value] = data_address;
330
331 lldb_private::Log *log(
332 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
333
334 if (log) {
335 log->Printf("Made an allocation for argument %s",
336 PrintValue(value).c_str());
337 log->Printf(" Data region : %llx", (unsigned long long)address);
338 log->Printf(" Ref region : %llx", (unsigned long long)data_address);
339 }
340
341 return true;
342 }
343
344 bool ResolveConstant(lldb::addr_t process_address, const Constant *constant) {
345 APInt resolved_value;
346
347 if (!ResolveConstantValue(resolved_value, constant))
348 return false;
349
350 size_t constant_size = m_target_data.getTypeStoreSize(constant->getType());
351 lldb_private::DataBufferHeap buf(constant_size, 0);
352
Zachary Turner97206d52017-05-12 04:51:55 +0000353 lldb_private::Status get_data_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000354
355 lldb_private::Scalar resolved_scalar(
356 resolved_value.zextOrTrunc(llvm::NextPowerOf2(constant_size) * 8));
357 if (!resolved_scalar.GetAsMemoryData(buf.GetBytes(), buf.GetByteSize(),
358 m_byte_order, get_data_error))
359 return false;
360
Zachary Turner97206d52017-05-12 04:51:55 +0000361 lldb_private::Status write_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000362
363 m_execution_unit.WriteMemory(process_address, buf.GetBytes(),
364 buf.GetByteSize(), write_error);
365
366 return write_error.Success();
367 }
368
369 lldb::addr_t Malloc(size_t size, uint8_t byte_alignment) {
370 lldb::addr_t ret = m_stack_pointer;
371
372 ret -= size;
373 ret -= (ret % byte_alignment);
374
375 if (ret < m_frame_process_address)
376 return LLDB_INVALID_ADDRESS;
377
378 m_stack_pointer = ret;
379 return ret;
380 }
381
Kate Stoneb9c1b512016-09-06 20:57:50 +0000382 lldb::addr_t Malloc(llvm::Type *type) {
Zachary Turner97206d52017-05-12 04:51:55 +0000383 lldb_private::Status alloc_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000384
385 return Malloc(m_target_data.getTypeAllocSize(type),
386 m_target_data.getPrefTypeAlignment(type));
387 }
388
389 std::string PrintData(lldb::addr_t addr, llvm::Type *type) {
390 size_t length = m_target_data.getTypeStoreSize(type);
391
392 lldb_private::DataBufferHeap buf(length, 0);
393
Zachary Turner97206d52017-05-12 04:51:55 +0000394 lldb_private::Status read_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000395
396 m_execution_unit.ReadMemory(buf.GetBytes(), addr, length, read_error);
397
398 if (!read_error.Success())
399 return std::string("<couldn't read data>");
400
401 lldb_private::StreamString ss;
402
403 for (size_t i = 0; i < length; i++) {
404 if ((!(i & 0xf)) && i)
405 ss.Printf("%02hhx - ", buf.GetBytes()[i]);
406 else
407 ss.Printf("%02hhx ", buf.GetBytes()[i]);
408 }
409
410 return ss.GetString();
411 }
412
413 lldb::addr_t ResolveValue(const Value *value, Module &module) {
414 ValueMap::iterator i = m_values.find(value);
415
416 if (i != m_values.end())
417 return i->second;
418
419 // Fall back and allocate space [allocation type Alloca]
420
421 lldb::addr_t data_address = Malloc(value->getType());
422
423 if (const Constant *constant = dyn_cast<Constant>(value)) {
424 if (!ResolveConstant(data_address, constant)) {
Zachary Turner97206d52017-05-12 04:51:55 +0000425 lldb_private::Status free_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000426 m_execution_unit.Free(data_address, free_error);
427 return LLDB_INVALID_ADDRESS;
428 }
429 }
430
431 m_values[value] = data_address;
432 return data_address;
433 }
434};
435
436static const char *unsupported_opcode_error =
437 "Interpreter doesn't handle one of the expression's opcodes";
438static const char *unsupported_operand_error =
439 "Interpreter doesn't handle one of the expression's operands";
440// static const char *interpreter_initialization_error = "Interpreter couldn't
441// be initialized";
442static const char *interpreter_internal_error =
443 "Interpreter encountered an internal error";
444static const char *bad_value_error =
445 "Interpreter couldn't resolve a value during execution";
446static const char *memory_allocation_error =
447 "Interpreter couldn't allocate memory";
448static const char *memory_write_error = "Interpreter couldn't write to memory";
449static const char *memory_read_error = "Interpreter couldn't read from memory";
450static const char *infinite_loop_error = "Interpreter ran for too many cycles";
451// static const char *bad_result_error = "Result of expression
452// is in bad memory";
453static const char *too_many_functions_error =
454 "Interpreter doesn't handle modules with multiple function bodies.";
455
456static bool CanResolveConstant(llvm::Constant *constant) {
457 switch (constant->getValueID()) {
458 default:
459 return false;
460 case Value::ConstantIntVal:
461 case Value::ConstantFPVal:
462 case Value::FunctionVal:
463 return true;
464 case Value::ConstantExprVal:
465 if (const ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(constant)) {
466 switch (constant_expr->getOpcode()) {
467 default:
468 return false;
469 case Instruction::IntToPtr:
470 case Instruction::PtrToInt:
471 case Instruction::BitCast:
472 return CanResolveConstant(constant_expr->getOperand(0));
473 case Instruction::GetElementPtr: {
474 ConstantExpr::const_op_iterator op_cursor = constant_expr->op_begin();
475 Constant *base = dyn_cast<Constant>(*op_cursor);
476 if (!base)
477 return false;
478
479 return CanResolveConstant(base);
480 }
481 }
482 } else {
483 return false;
484 }
485 case Value::ConstantPointerNullVal:
486 return true;
487 }
488}
489
490bool IRInterpreter::CanInterpret(llvm::Module &module, llvm::Function &function,
Zachary Turner97206d52017-05-12 04:51:55 +0000491 lldb_private::Status &error,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000492 const bool support_function_calls) {
493 lldb_private::Log *log(
494 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
495
496 bool saw_function_with_body = false;
497
498 for (Module::iterator fi = module.begin(), fe = module.end(); fi != fe;
499 ++fi) {
500 if (fi->begin() != fi->end()) {
501 if (saw_function_with_body) {
502 if (log)
503 log->Printf("More than one function in the module has a body");
504 error.SetErrorToGenericError();
505 error.SetErrorString(too_many_functions_error);
506 return false;
507 }
508 saw_function_with_body = true;
509 }
510 }
511
512 for (Function::iterator bbi = function.begin(), bbe = function.end();
513 bbi != bbe; ++bbi) {
514 for (BasicBlock::iterator ii = bbi->begin(), ie = bbi->end(); ii != ie;
515 ++ii) {
516 switch (ii->getOpcode()) {
517 default: {
518 if (log)
519 log->Printf("Unsupported instruction: %s", PrintValue(&*ii).c_str());
520 error.SetErrorToGenericError();
521 error.SetErrorString(unsupported_opcode_error);
522 return false;
523 }
524 case Instruction::Add:
525 case Instruction::Alloca:
526 case Instruction::BitCast:
527 case Instruction::Br:
528 case Instruction::PHI:
529 break;
530 case Instruction::Call: {
531 CallInst *call_inst = dyn_cast<CallInst>(ii);
532
533 if (!call_inst) {
534 error.SetErrorToGenericError();
535 error.SetErrorString(interpreter_internal_error);
536 return false;
537 }
538
539 if (!CanIgnoreCall(call_inst) && !support_function_calls) {
540 if (log)
541 log->Printf("Unsupported instruction: %s",
542 PrintValue(&*ii).c_str());
543 error.SetErrorToGenericError();
544 error.SetErrorString(unsupported_opcode_error);
545 return false;
546 }
547 } break;
548 case Instruction::GetElementPtr:
549 break;
550 case Instruction::ICmp: {
551 ICmpInst *icmp_inst = dyn_cast<ICmpInst>(ii);
552
553 if (!icmp_inst) {
554 error.SetErrorToGenericError();
555 error.SetErrorString(interpreter_internal_error);
556 return false;
557 }
558
559 switch (icmp_inst->getPredicate()) {
560 default: {
561 if (log)
562 log->Printf("Unsupported ICmp predicate: %s",
563 PrintValue(&*ii).c_str());
564
565 error.SetErrorToGenericError();
566 error.SetErrorString(unsupported_opcode_error);
567 return false;
568 }
569 case CmpInst::ICMP_EQ:
570 case CmpInst::ICMP_NE:
571 case CmpInst::ICMP_UGT:
572 case CmpInst::ICMP_UGE:
573 case CmpInst::ICMP_ULT:
574 case CmpInst::ICMP_ULE:
575 case CmpInst::ICMP_SGT:
576 case CmpInst::ICMP_SGE:
577 case CmpInst::ICMP_SLT:
578 case CmpInst::ICMP_SLE:
579 break;
580 }
581 } break;
582 case Instruction::And:
583 case Instruction::AShr:
584 case Instruction::IntToPtr:
585 case Instruction::PtrToInt:
586 case Instruction::Load:
587 case Instruction::LShr:
588 case Instruction::Mul:
589 case Instruction::Or:
590 case Instruction::Ret:
591 case Instruction::SDiv:
592 case Instruction::SExt:
593 case Instruction::Shl:
594 case Instruction::SRem:
595 case Instruction::Store:
596 case Instruction::Sub:
597 case Instruction::Trunc:
598 case Instruction::UDiv:
599 case Instruction::URem:
600 case Instruction::Xor:
601 case Instruction::ZExt:
602 break;
603 }
604
605 for (int oi = 0, oe = ii->getNumOperands(); oi != oe; ++oi) {
606 Value *operand = ii->getOperand(oi);
607 Type *operand_type = operand->getType();
608
609 switch (operand_type->getTypeID()) {
610 default:
611 break;
612 case Type::VectorTyID: {
613 if (log)
614 log->Printf("Unsupported operand type: %s",
615 PrintType(operand_type).c_str());
616 error.SetErrorString(unsupported_operand_error);
617 return false;
618 }
619 }
620
621 if (Constant *constant = llvm::dyn_cast<Constant>(operand)) {
622 if (!CanResolveConstant(constant)) {
623 if (log)
624 log->Printf("Unsupported constant: %s",
625 PrintValue(constant).c_str());
626 error.SetErrorString(unsupported_operand_error);
627 return false;
628 }
629 }
630 }
631 }
632 }
633
634 return true;
635}
636
637bool IRInterpreter::Interpret(llvm::Module &module, llvm::Function &function,
638 llvm::ArrayRef<lldb::addr_t> args,
639 lldb_private::IRExecutionUnit &execution_unit,
Zachary Turner97206d52017-05-12 04:51:55 +0000640 lldb_private::Status &error,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000641 lldb::addr_t stack_frame_bottom,
642 lldb::addr_t stack_frame_top,
643 lldb_private::ExecutionContext &exe_ctx) {
644 lldb_private::Log *log(
645 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
646
647 if (log) {
648 std::string s;
649 raw_string_ostream oss(s);
650
651 module.print(oss, NULL);
652
653 oss.flush();
654
655 log->Printf("Module as passed in to IRInterpreter::Interpret: \n\"%s\"",
656 s.c_str());
657 }
658
659 DataLayout data_layout(&module);
660
661 InterpreterStackFrame frame(data_layout, execution_unit, stack_frame_bottom,
662 stack_frame_top);
663
664 if (frame.m_frame_process_address == LLDB_INVALID_ADDRESS) {
665 error.SetErrorString("Couldn't allocate stack frame");
666 }
667
668 int arg_index = 0;
669
670 for (llvm::Function::arg_iterator ai = function.arg_begin(),
671 ae = function.arg_end();
672 ai != ae; ++ai, ++arg_index) {
673 if (args.size() <= static_cast<size_t>(arg_index)) {
674 error.SetErrorString("Not enough arguments passed in to function");
675 return false;
676 }
677
678 lldb::addr_t ptr = args[arg_index];
679
680 frame.MakeArgument(&*ai, ptr);
681 }
682
683 uint32_t num_insts = 0;
684
685 frame.Jump(&function.front());
686
687 while (frame.m_ii != frame.m_ie && (++num_insts < 4096)) {
688 const Instruction *inst = &*frame.m_ii;
689
690 if (log)
691 log->Printf("Interpreting %s", PrintValue(inst).c_str());
692
693 switch (inst->getOpcode()) {
694 default:
695 break;
696
697 case Instruction::Add:
698 case Instruction::Sub:
699 case Instruction::Mul:
700 case Instruction::SDiv:
701 case Instruction::UDiv:
702 case Instruction::SRem:
703 case Instruction::URem:
704 case Instruction::Shl:
705 case Instruction::LShr:
706 case Instruction::AShr:
707 case Instruction::And:
708 case Instruction::Or:
709 case Instruction::Xor: {
710 const BinaryOperator *bin_op = dyn_cast<BinaryOperator>(inst);
711
712 if (!bin_op) {
713 if (log)
714 log->Printf(
715 "getOpcode() returns %s, but instruction is not a BinaryOperator",
716 inst->getOpcodeName());
717 error.SetErrorToGenericError();
718 error.SetErrorString(interpreter_internal_error);
719 return false;
720 }
721
722 Value *lhs = inst->getOperand(0);
723 Value *rhs = inst->getOperand(1);
724
725 lldb_private::Scalar L;
726 lldb_private::Scalar R;
727
728 if (!frame.EvaluateValue(L, lhs, module)) {
729 if (log)
730 log->Printf("Couldn't evaluate %s", PrintValue(lhs).c_str());
731 error.SetErrorToGenericError();
732 error.SetErrorString(bad_value_error);
733 return false;
734 }
735
736 if (!frame.EvaluateValue(R, rhs, module)) {
737 if (log)
738 log->Printf("Couldn't evaluate %s", PrintValue(rhs).c_str());
739 error.SetErrorToGenericError();
740 error.SetErrorString(bad_value_error);
741 return false;
742 }
743
744 lldb_private::Scalar result;
745
746 switch (inst->getOpcode()) {
747 default:
748 break;
749 case Instruction::Add:
750 result = L + R;
751 break;
752 case Instruction::Mul:
753 result = L * R;
754 break;
755 case Instruction::Sub:
756 result = L - R;
757 break;
758 case Instruction::SDiv:
759 L.MakeSigned();
760 R.MakeSigned();
761 result = L / R;
762 break;
763 case Instruction::UDiv:
764 L.MakeUnsigned();
765 R.MakeUnsigned();
766 result = L / R;
767 break;
768 case Instruction::SRem:
769 L.MakeSigned();
770 R.MakeSigned();
771 result = L % R;
772 break;
773 case Instruction::URem:
774 L.MakeUnsigned();
775 R.MakeUnsigned();
776 result = L % R;
777 break;
778 case Instruction::Shl:
779 result = L << R;
780 break;
781 case Instruction::AShr:
782 result = L >> R;
783 break;
784 case Instruction::LShr:
785 result = L;
786 result.ShiftRightLogical(R);
787 break;
788 case Instruction::And:
789 result = L & R;
790 break;
791 case Instruction::Or:
792 result = L | R;
793 break;
794 case Instruction::Xor:
795 result = L ^ R;
796 break;
797 }
798
799 frame.AssignValue(inst, result, module);
800
801 if (log) {
802 log->Printf("Interpreted a %s", inst->getOpcodeName());
803 log->Printf(" L : %s", frame.SummarizeValue(lhs).c_str());
804 log->Printf(" R : %s", frame.SummarizeValue(rhs).c_str());
805 log->Printf(" = : %s", frame.SummarizeValue(inst).c_str());
806 }
807 } break;
808 case Instruction::Alloca: {
809 const AllocaInst *alloca_inst = dyn_cast<AllocaInst>(inst);
810
811 if (!alloca_inst) {
812 if (log)
813 log->Printf("getOpcode() returns Alloca, but instruction is not an "
814 "AllocaInst");
815 error.SetErrorToGenericError();
816 error.SetErrorString(interpreter_internal_error);
817 return false;
818 }
819
820 if (alloca_inst->isArrayAllocation()) {
821 if (log)
822 log->Printf(
823 "AllocaInsts are not handled if isArrayAllocation() is true");
824 error.SetErrorToGenericError();
825 error.SetErrorString(unsupported_opcode_error);
826 return false;
827 }
828
829 // The semantics of Alloca are:
830 // Create a region R of virtual memory of type T, backed by a data
831 // buffer
832 // Create a region P of virtual memory of type T*, backed by a data
833 // buffer
834 // Write the virtual address of R into P
835
836 Type *T = alloca_inst->getAllocatedType();
837 Type *Tptr = alloca_inst->getType();
838
839 lldb::addr_t R = frame.Malloc(T);
840
841 if (R == LLDB_INVALID_ADDRESS) {
842 if (log)
843 log->Printf("Couldn't allocate memory for an AllocaInst");
844 error.SetErrorToGenericError();
845 error.SetErrorString(memory_allocation_error);
846 return false;
847 }
848
849 lldb::addr_t P = frame.Malloc(Tptr);
850
851 if (P == LLDB_INVALID_ADDRESS) {
852 if (log)
853 log->Printf("Couldn't allocate the result pointer for an AllocaInst");
854 error.SetErrorToGenericError();
855 error.SetErrorString(memory_allocation_error);
856 return false;
857 }
858
Zachary Turner97206d52017-05-12 04:51:55 +0000859 lldb_private::Status write_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000860
861 execution_unit.WritePointerToMemory(P, R, write_error);
862
863 if (!write_error.Success()) {
864 if (log)
865 log->Printf("Couldn't write the result pointer for an AllocaInst");
866 error.SetErrorToGenericError();
867 error.SetErrorString(memory_write_error);
Zachary Turner97206d52017-05-12 04:51:55 +0000868 lldb_private::Status free_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000869 execution_unit.Free(P, free_error);
870 execution_unit.Free(R, free_error);
871 return false;
872 }
873
874 frame.m_values[alloca_inst] = P;
875
876 if (log) {
877 log->Printf("Interpreted an AllocaInst");
878 log->Printf(" R : 0x%" PRIx64, R);
879 log->Printf(" P : 0x%" PRIx64, P);
880 }
881 } break;
882 case Instruction::BitCast:
883 case Instruction::ZExt: {
884 const CastInst *cast_inst = dyn_cast<CastInst>(inst);
885
886 if (!cast_inst) {
887 if (log)
888 log->Printf(
889 "getOpcode() returns %s, but instruction is not a BitCastInst",
890 cast_inst->getOpcodeName());
891 error.SetErrorToGenericError();
892 error.SetErrorString(interpreter_internal_error);
893 return false;
894 }
895
896 Value *source = cast_inst->getOperand(0);
897
898 lldb_private::Scalar S;
899
900 if (!frame.EvaluateValue(S, source, module)) {
901 if (log)
902 log->Printf("Couldn't evaluate %s", PrintValue(source).c_str());
903 error.SetErrorToGenericError();
904 error.SetErrorString(bad_value_error);
905 return false;
906 }
907
908 frame.AssignValue(inst, S, module);
909 } break;
910 case Instruction::SExt: {
911 const CastInst *cast_inst = dyn_cast<CastInst>(inst);
912
913 if (!cast_inst) {
914 if (log)
915 log->Printf(
916 "getOpcode() returns %s, but instruction is not a BitCastInst",
917 cast_inst->getOpcodeName());
918 error.SetErrorToGenericError();
919 error.SetErrorString(interpreter_internal_error);
920 return false;
921 }
922
923 Value *source = cast_inst->getOperand(0);
924
925 lldb_private::Scalar S;
926
927 if (!frame.EvaluateValue(S, source, module)) {
928 if (log)
929 log->Printf("Couldn't evaluate %s", PrintValue(source).c_str());
930 error.SetErrorToGenericError();
931 error.SetErrorString(bad_value_error);
932 return false;
933 }
934
935 S.MakeSigned();
936
937 lldb_private::Scalar S_signextend(S.SLongLong());
938
939 frame.AssignValue(inst, S_signextend, module);
940 } break;
941 case Instruction::Br: {
942 const BranchInst *br_inst = dyn_cast<BranchInst>(inst);
943
944 if (!br_inst) {
945 if (log)
946 log->Printf(
947 "getOpcode() returns Br, but instruction is not a BranchInst");
948 error.SetErrorToGenericError();
949 error.SetErrorString(interpreter_internal_error);
950 return false;
951 }
952
953 if (br_inst->isConditional()) {
954 Value *condition = br_inst->getCondition();
955
956 lldb_private::Scalar C;
957
958 if (!frame.EvaluateValue(C, condition, module)) {
959 if (log)
960 log->Printf("Couldn't evaluate %s", PrintValue(condition).c_str());
961 error.SetErrorToGenericError();
962 error.SetErrorString(bad_value_error);
963 return false;
964 }
965
966 if (!C.IsZero())
967 frame.Jump(br_inst->getSuccessor(0));
968 else
969 frame.Jump(br_inst->getSuccessor(1));
970
971 if (log) {
972 log->Printf("Interpreted a BrInst with a condition");
973 log->Printf(" cond : %s", frame.SummarizeValue(condition).c_str());
974 }
975 } else {
976 frame.Jump(br_inst->getSuccessor(0));
977
978 if (log) {
979 log->Printf("Interpreted a BrInst with no condition");
980 }
981 }
982 }
983 continue;
984 case Instruction::PHI: {
985 const PHINode *phi_inst = dyn_cast<PHINode>(inst);
986
987 if (!phi_inst) {
988 if (log)
989 log->Printf(
990 "getOpcode() returns PHI, but instruction is not a PHINode");
991 error.SetErrorToGenericError();
992 error.SetErrorString(interpreter_internal_error);
993 return false;
994 }
995 if (!frame.m_prev_bb) {
996 if (log)
997 log->Printf("Encountered PHI node without having jumped from another "
998 "basic block");
999 error.SetErrorToGenericError();
1000 error.SetErrorString(interpreter_internal_error);
1001 return false;
1002 }
1003
1004 Value *value = phi_inst->getIncomingValueForBlock(frame.m_prev_bb);
1005 lldb_private::Scalar result;
1006 if (!frame.EvaluateValue(result, value, module)) {
1007 if (log)
1008 log->Printf("Couldn't evaluate %s", PrintValue(value).c_str());
1009 error.SetErrorToGenericError();
1010 error.SetErrorString(bad_value_error);
1011 return false;
1012 }
1013 frame.AssignValue(inst, result, module);
1014
1015 if (log) {
1016 log->Printf("Interpreted a %s", inst->getOpcodeName());
1017 log->Printf(" Incoming value : %s",
1018 frame.SummarizeValue(value).c_str());
1019 }
1020 } break;
1021 case Instruction::GetElementPtr: {
1022 const GetElementPtrInst *gep_inst = dyn_cast<GetElementPtrInst>(inst);
1023
1024 if (!gep_inst) {
1025 if (log)
1026 log->Printf("getOpcode() returns GetElementPtr, but instruction is "
1027 "not a GetElementPtrInst");
1028 error.SetErrorToGenericError();
1029 error.SetErrorString(interpreter_internal_error);
1030 return false;
1031 }
1032
1033 const Value *pointer_operand = gep_inst->getPointerOperand();
1034 Type *src_elem_ty = gep_inst->getSourceElementType();
1035
1036 lldb_private::Scalar P;
1037
1038 if (!frame.EvaluateValue(P, pointer_operand, module)) {
1039 if (log)
1040 log->Printf("Couldn't evaluate %s",
1041 PrintValue(pointer_operand).c_str());
1042 error.SetErrorToGenericError();
1043 error.SetErrorString(bad_value_error);
1044 return false;
1045 }
1046
1047 typedef SmallVector<Value *, 8> IndexVector;
1048 typedef IndexVector::iterator IndexIterator;
1049
1050 SmallVector<Value *, 8> indices(gep_inst->idx_begin(),
1051 gep_inst->idx_end());
1052
1053 SmallVector<Value *, 8> const_indices;
1054
1055 for (IndexIterator ii = indices.begin(), ie = indices.end(); ii != ie;
1056 ++ii) {
1057 ConstantInt *constant_index = dyn_cast<ConstantInt>(*ii);
1058
1059 if (!constant_index) {
1060 lldb_private::Scalar I;
1061
1062 if (!frame.EvaluateValue(I, *ii, module)) {
1063 if (log)
1064 log->Printf("Couldn't evaluate %s", PrintValue(*ii).c_str());
1065 error.SetErrorToGenericError();
1066 error.SetErrorString(bad_value_error);
1067 return false;
1068 }
1069
1070 if (log)
1071 log->Printf("Evaluated constant index %s as %llu",
1072 PrintValue(*ii).c_str(),
1073 I.ULongLong(LLDB_INVALID_ADDRESS));
1074
1075 constant_index = cast<ConstantInt>(ConstantInt::get(
1076 (*ii)->getType(), I.ULongLong(LLDB_INVALID_ADDRESS)));
1077 }
1078
1079 const_indices.push_back(constant_index);
1080 }
1081
1082 uint64_t offset =
1083 data_layout.getIndexedOffsetInType(src_elem_ty, const_indices);
1084
1085 lldb_private::Scalar Poffset = P + offset;
1086
1087 frame.AssignValue(inst, Poffset, module);
1088
1089 if (log) {
1090 log->Printf("Interpreted a GetElementPtrInst");
1091 log->Printf(" P : %s",
1092 frame.SummarizeValue(pointer_operand).c_str());
1093 log->Printf(" Poffset : %s", frame.SummarizeValue(inst).c_str());
1094 }
1095 } break;
1096 case Instruction::ICmp: {
1097 const ICmpInst *icmp_inst = dyn_cast<ICmpInst>(inst);
1098
1099 if (!icmp_inst) {
1100 if (log)
1101 log->Printf(
1102 "getOpcode() returns ICmp, but instruction is not an ICmpInst");
1103 error.SetErrorToGenericError();
1104 error.SetErrorString(interpreter_internal_error);
1105 return false;
1106 }
1107
1108 CmpInst::Predicate predicate = icmp_inst->getPredicate();
1109
1110 Value *lhs = inst->getOperand(0);
1111 Value *rhs = inst->getOperand(1);
1112
1113 lldb_private::Scalar L;
1114 lldb_private::Scalar R;
1115
1116 if (!frame.EvaluateValue(L, lhs, module)) {
1117 if (log)
1118 log->Printf("Couldn't evaluate %s", PrintValue(lhs).c_str());
1119 error.SetErrorToGenericError();
1120 error.SetErrorString(bad_value_error);
1121 return false;
1122 }
1123
1124 if (!frame.EvaluateValue(R, rhs, module)) {
1125 if (log)
1126 log->Printf("Couldn't evaluate %s", PrintValue(rhs).c_str());
1127 error.SetErrorToGenericError();
1128 error.SetErrorString(bad_value_error);
1129 return false;
1130 }
1131
1132 lldb_private::Scalar result;
1133
1134 switch (predicate) {
1135 default:
1136 return false;
1137 case CmpInst::ICMP_EQ:
1138 result = (L == R);
1139 break;
1140 case CmpInst::ICMP_NE:
1141 result = (L != R);
1142 break;
1143 case CmpInst::ICMP_UGT:
1144 L.MakeUnsigned();
1145 R.MakeUnsigned();
1146 result = (L > R);
1147 break;
1148 case CmpInst::ICMP_UGE:
1149 L.MakeUnsigned();
1150 R.MakeUnsigned();
1151 result = (L >= R);
1152 break;
1153 case CmpInst::ICMP_ULT:
1154 L.MakeUnsigned();
1155 R.MakeUnsigned();
1156 result = (L < R);
1157 break;
1158 case CmpInst::ICMP_ULE:
1159 L.MakeUnsigned();
1160 R.MakeUnsigned();
1161 result = (L <= R);
1162 break;
1163 case CmpInst::ICMP_SGT:
1164 L.MakeSigned();
1165 R.MakeSigned();
1166 result = (L > R);
1167 break;
1168 case CmpInst::ICMP_SGE:
1169 L.MakeSigned();
1170 R.MakeSigned();
1171 result = (L >= R);
1172 break;
1173 case CmpInst::ICMP_SLT:
1174 L.MakeSigned();
1175 R.MakeSigned();
1176 result = (L < R);
1177 break;
1178 case CmpInst::ICMP_SLE:
1179 L.MakeSigned();
1180 R.MakeSigned();
1181 result = (L <= R);
1182 break;
1183 }
1184
1185 frame.AssignValue(inst, result, module);
1186
1187 if (log) {
1188 log->Printf("Interpreted an ICmpInst");
1189 log->Printf(" L : %s", frame.SummarizeValue(lhs).c_str());
1190 log->Printf(" R : %s", frame.SummarizeValue(rhs).c_str());
1191 log->Printf(" = : %s", frame.SummarizeValue(inst).c_str());
1192 }
1193 } break;
1194 case Instruction::IntToPtr: {
1195 const IntToPtrInst *int_to_ptr_inst = dyn_cast<IntToPtrInst>(inst);
1196
1197 if (!int_to_ptr_inst) {
1198 if (log)
1199 log->Printf("getOpcode() returns IntToPtr, but instruction is not an "
1200 "IntToPtrInst");
1201 error.SetErrorToGenericError();
1202 error.SetErrorString(interpreter_internal_error);
1203 return false;
1204 }
1205
1206 Value *src_operand = int_to_ptr_inst->getOperand(0);
1207
1208 lldb_private::Scalar I;
1209
1210 if (!frame.EvaluateValue(I, src_operand, module)) {
1211 if (log)
1212 log->Printf("Couldn't evaluate %s", PrintValue(src_operand).c_str());
1213 error.SetErrorToGenericError();
1214 error.SetErrorString(bad_value_error);
1215 return false;
1216 }
1217
1218 frame.AssignValue(inst, I, module);
1219
1220 if (log) {
1221 log->Printf("Interpreted an IntToPtr");
1222 log->Printf(" Src : %s", frame.SummarizeValue(src_operand).c_str());
1223 log->Printf(" = : %s", frame.SummarizeValue(inst).c_str());
1224 }
1225 } break;
1226 case Instruction::PtrToInt: {
1227 const PtrToIntInst *ptr_to_int_inst = dyn_cast<PtrToIntInst>(inst);
1228
1229 if (!ptr_to_int_inst) {
1230 if (log)
1231 log->Printf("getOpcode() returns PtrToInt, but instruction is not an "
1232 "PtrToIntInst");
1233 error.SetErrorToGenericError();
1234 error.SetErrorString(interpreter_internal_error);
1235 return false;
1236 }
1237
1238 Value *src_operand = ptr_to_int_inst->getOperand(0);
1239
1240 lldb_private::Scalar I;
1241
1242 if (!frame.EvaluateValue(I, src_operand, module)) {
1243 if (log)
1244 log->Printf("Couldn't evaluate %s", PrintValue(src_operand).c_str());
1245 error.SetErrorToGenericError();
1246 error.SetErrorString(bad_value_error);
1247 return false;
1248 }
1249
1250 frame.AssignValue(inst, I, module);
1251
1252 if (log) {
1253 log->Printf("Interpreted a PtrToInt");
1254 log->Printf(" Src : %s", frame.SummarizeValue(src_operand).c_str());
1255 log->Printf(" = : %s", frame.SummarizeValue(inst).c_str());
1256 }
1257 } break;
1258 case Instruction::Trunc: {
1259 const TruncInst *trunc_inst = dyn_cast<TruncInst>(inst);
1260
1261 if (!trunc_inst) {
1262 if (log)
1263 log->Printf(
1264 "getOpcode() returns Trunc, but instruction is not a TruncInst");
1265 error.SetErrorToGenericError();
1266 error.SetErrorString(interpreter_internal_error);
1267 return false;
1268 }
1269
1270 Value *src_operand = trunc_inst->getOperand(0);
1271
1272 lldb_private::Scalar I;
1273
1274 if (!frame.EvaluateValue(I, src_operand, module)) {
1275 if (log)
1276 log->Printf("Couldn't evaluate %s", PrintValue(src_operand).c_str());
1277 error.SetErrorToGenericError();
1278 error.SetErrorString(bad_value_error);
1279 return false;
1280 }
1281
1282 frame.AssignValue(inst, I, module);
1283
1284 if (log) {
1285 log->Printf("Interpreted a Trunc");
1286 log->Printf(" Src : %s", frame.SummarizeValue(src_operand).c_str());
1287 log->Printf(" = : %s", frame.SummarizeValue(inst).c_str());
1288 }
1289 } break;
1290 case Instruction::Load: {
1291 const LoadInst *load_inst = dyn_cast<LoadInst>(inst);
1292
1293 if (!load_inst) {
1294 if (log)
1295 log->Printf(
1296 "getOpcode() returns Load, but instruction is not a LoadInst");
1297 error.SetErrorToGenericError();
1298 error.SetErrorString(interpreter_internal_error);
1299 return false;
1300 }
1301
1302 // The semantics of Load are:
1303 // Create a region D that will contain the loaded data
1304 // Resolve the region P containing a pointer
1305 // Dereference P to get the region R that the data should be loaded from
1306 // Transfer a unit of type type(D) from R to D
1307
1308 const Value *pointer_operand = load_inst->getPointerOperand();
1309
1310 Type *pointer_ty = pointer_operand->getType();
1311 PointerType *pointer_ptr_ty = dyn_cast<PointerType>(pointer_ty);
1312 if (!pointer_ptr_ty) {
1313 if (log)
1314 log->Printf("getPointerOperand()->getType() is not a PointerType");
1315 error.SetErrorToGenericError();
1316 error.SetErrorString(interpreter_internal_error);
1317 return false;
1318 }
1319 Type *target_ty = pointer_ptr_ty->getElementType();
1320
1321 lldb::addr_t D = frame.ResolveValue(load_inst, module);
1322 lldb::addr_t P = frame.ResolveValue(pointer_operand, module);
1323
1324 if (D == LLDB_INVALID_ADDRESS) {
1325 if (log)
1326 log->Printf("LoadInst's value doesn't resolve to anything");
1327 error.SetErrorToGenericError();
1328 error.SetErrorString(bad_value_error);
1329 return false;
1330 }
1331
1332 if (P == LLDB_INVALID_ADDRESS) {
1333 if (log)
1334 log->Printf("LoadInst's pointer doesn't resolve to anything");
1335 error.SetErrorToGenericError();
1336 error.SetErrorString(bad_value_error);
1337 return false;
1338 }
1339
1340 lldb::addr_t R;
Zachary Turner97206d52017-05-12 04:51:55 +00001341 lldb_private::Status read_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001342 execution_unit.ReadPointerFromMemory(&R, P, read_error);
1343
1344 if (!read_error.Success()) {
1345 if (log)
1346 log->Printf("Couldn't read the address to be loaded for a LoadInst");
1347 error.SetErrorToGenericError();
1348 error.SetErrorString(memory_read_error);
1349 return false;
1350 }
1351
1352 size_t target_size = data_layout.getTypeStoreSize(target_ty);
1353 lldb_private::DataBufferHeap buffer(target_size, 0);
1354
1355 read_error.Clear();
1356 execution_unit.ReadMemory(buffer.GetBytes(), R, buffer.GetByteSize(),
1357 read_error);
1358 if (!read_error.Success()) {
1359 if (log)
1360 log->Printf("Couldn't read from a region on behalf of a LoadInst");
1361 error.SetErrorToGenericError();
1362 error.SetErrorString(memory_read_error);
1363 return false;
1364 }
1365
Zachary Turner97206d52017-05-12 04:51:55 +00001366 lldb_private::Status write_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001367 execution_unit.WriteMemory(D, buffer.GetBytes(), buffer.GetByteSize(),
1368 write_error);
1369 if (!write_error.Success()) {
1370 if (log)
1371 log->Printf("Couldn't write to a region on behalf of a LoadInst");
1372 error.SetErrorToGenericError();
1373 error.SetErrorString(memory_read_error);
1374 return false;
1375 }
1376
1377 if (log) {
1378 log->Printf("Interpreted a LoadInst");
1379 log->Printf(" P : 0x%" PRIx64, P);
1380 log->Printf(" R : 0x%" PRIx64, R);
1381 log->Printf(" D : 0x%" PRIx64, D);
1382 }
1383 } break;
1384 case Instruction::Ret: {
1385 return true;
1386 }
1387 case Instruction::Store: {
1388 const StoreInst *store_inst = dyn_cast<StoreInst>(inst);
1389
1390 if (!store_inst) {
1391 if (log)
1392 log->Printf(
1393 "getOpcode() returns Store, but instruction is not a StoreInst");
1394 error.SetErrorToGenericError();
1395 error.SetErrorString(interpreter_internal_error);
1396 return false;
1397 }
1398
1399 // The semantics of Store are:
1400 // Resolve the region D containing the data to be stored
1401 // Resolve the region P containing a pointer
1402 // Dereference P to get the region R that the data should be stored in
1403 // Transfer a unit of type type(D) from D to R
1404
1405 const Value *value_operand = store_inst->getValueOperand();
1406 const Value *pointer_operand = store_inst->getPointerOperand();
1407
1408 Type *pointer_ty = pointer_operand->getType();
1409 PointerType *pointer_ptr_ty = dyn_cast<PointerType>(pointer_ty);
1410 if (!pointer_ptr_ty)
1411 return false;
1412 Type *target_ty = pointer_ptr_ty->getElementType();
1413
1414 lldb::addr_t D = frame.ResolveValue(value_operand, module);
1415 lldb::addr_t P = frame.ResolveValue(pointer_operand, module);
1416
1417 if (D == LLDB_INVALID_ADDRESS) {
1418 if (log)
1419 log->Printf("StoreInst's value doesn't resolve to anything");
1420 error.SetErrorToGenericError();
1421 error.SetErrorString(bad_value_error);
1422 return false;
1423 }
1424
1425 if (P == LLDB_INVALID_ADDRESS) {
1426 if (log)
1427 log->Printf("StoreInst's pointer doesn't resolve to anything");
1428 error.SetErrorToGenericError();
1429 error.SetErrorString(bad_value_error);
1430 return false;
1431 }
1432
1433 lldb::addr_t R;
Zachary Turner97206d52017-05-12 04:51:55 +00001434 lldb_private::Status read_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001435 execution_unit.ReadPointerFromMemory(&R, P, read_error);
1436
1437 if (!read_error.Success()) {
1438 if (log)
1439 log->Printf("Couldn't read the address to be loaded for a LoadInst");
1440 error.SetErrorToGenericError();
1441 error.SetErrorString(memory_read_error);
1442 return false;
1443 }
1444
1445 size_t target_size = data_layout.getTypeStoreSize(target_ty);
1446 lldb_private::DataBufferHeap buffer(target_size, 0);
1447
1448 read_error.Clear();
1449 execution_unit.ReadMemory(buffer.GetBytes(), D, buffer.GetByteSize(),
1450 read_error);
1451 if (!read_error.Success()) {
1452 if (log)
1453 log->Printf("Couldn't read from a region on behalf of a StoreInst");
1454 error.SetErrorToGenericError();
1455 error.SetErrorString(memory_read_error);
1456 return false;
1457 }
1458
Zachary Turner97206d52017-05-12 04:51:55 +00001459 lldb_private::Status write_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001460 execution_unit.WriteMemory(R, buffer.GetBytes(), buffer.GetByteSize(),
1461 write_error);
1462 if (!write_error.Success()) {
1463 if (log)
1464 log->Printf("Couldn't write to a region on behalf of a StoreInst");
1465 error.SetErrorToGenericError();
1466 error.SetErrorString(memory_write_error);
1467 return false;
1468 }
1469
1470 if (log) {
1471 log->Printf("Interpreted a StoreInst");
1472 log->Printf(" D : 0x%" PRIx64, D);
1473 log->Printf(" P : 0x%" PRIx64, P);
1474 log->Printf(" R : 0x%" PRIx64, R);
1475 }
1476 } break;
1477 case Instruction::Call: {
1478 const CallInst *call_inst = dyn_cast<CallInst>(inst);
1479
1480 if (!call_inst) {
1481 if (log)
1482 log->Printf(
1483 "getOpcode() returns %s, but instruction is not a CallInst",
1484 inst->getOpcodeName());
1485 error.SetErrorToGenericError();
1486 error.SetErrorString(interpreter_internal_error);
1487 return false;
1488 }
1489
1490 if (CanIgnoreCall(call_inst))
1491 break;
1492
1493 // Get the return type
1494 llvm::Type *returnType = call_inst->getType();
1495 if (returnType == nullptr) {
1496 error.SetErrorToGenericError();
1497 error.SetErrorString("unable to access return type");
1498 return false;
1499 }
1500
1501 // Work with void, integer and pointer return types
1502 if (!returnType->isVoidTy() && !returnType->isIntegerTy() &&
1503 !returnType->isPointerTy()) {
1504 error.SetErrorToGenericError();
1505 error.SetErrorString("return type is not supported");
1506 return false;
1507 }
1508
1509 // Check we can actually get a thread
1510 if (exe_ctx.GetThreadPtr() == nullptr) {
1511 error.SetErrorToGenericError();
1512 error.SetErrorStringWithFormat("unable to acquire thread");
1513 return false;
1514 }
1515
1516 // Make sure we have a valid process
1517 if (!exe_ctx.GetProcessPtr()) {
1518 error.SetErrorToGenericError();
1519 error.SetErrorStringWithFormat("unable to get the process");
1520 return false;
1521 }
1522
1523 // Find the address of the callee function
1524 lldb_private::Scalar I;
1525 const llvm::Value *val = call_inst->getCalledValue();
1526
1527 if (!frame.EvaluateValue(I, val, module)) {
1528 error.SetErrorToGenericError();
1529 error.SetErrorString("unable to get address of function");
1530 return false;
1531 }
1532 lldb_private::Address funcAddr(I.ULongLong(LLDB_INVALID_ADDRESS));
1533
1534 lldb_private::DiagnosticManager diagnostics;
1535 lldb_private::EvaluateExpressionOptions options;
1536
1537 // We generally receive a function pointer which we must dereference
1538 llvm::Type *prototype = val->getType();
1539 if (!prototype->isPointerTy()) {
1540 error.SetErrorToGenericError();
1541 error.SetErrorString("call need function pointer");
1542 return false;
1543 }
1544
1545 // Dereference the function pointer
1546 prototype = prototype->getPointerElementType();
1547 if (!(prototype->isFunctionTy() || prototype->isFunctionVarArg())) {
1548 error.SetErrorToGenericError();
1549 error.SetErrorString("call need function pointer");
1550 return false;
1551 }
1552
1553 // Find number of arguments
1554 const int numArgs = call_inst->getNumArgOperands();
1555
1556 // We work with a fixed array of 16 arguments which is our upper limit
1557 static lldb_private::ABI::CallArgument rawArgs[16];
1558 if (numArgs >= 16) {
1559 error.SetErrorToGenericError();
1560 error.SetErrorStringWithFormat("function takes too many arguments");
1561 return false;
1562 }
1563
Adrian Prantl05097242018-04-30 16:49:04 +00001564 // Push all function arguments to the argument list that will be passed
1565 // to the call function thread plan
Kate Stoneb9c1b512016-09-06 20:57:50 +00001566 for (int i = 0; i < numArgs; i++) {
1567 // Get details of this argument
1568 llvm::Value *arg_op = call_inst->getArgOperand(i);
1569 llvm::Type *arg_ty = arg_op->getType();
1570
1571 // Ensure that this argument is an supported type
1572 if (!arg_ty->isIntegerTy() && !arg_ty->isPointerTy()) {
1573 error.SetErrorToGenericError();
1574 error.SetErrorStringWithFormat("argument %d must be integer type", i);
1575 return false;
1576 }
1577
1578 // Extract the arguments value
1579 lldb_private::Scalar tmp_op = 0;
1580 if (!frame.EvaluateValue(tmp_op, arg_op, module)) {
1581 error.SetErrorToGenericError();
1582 error.SetErrorStringWithFormat("unable to evaluate argument %d", i);
1583 return false;
1584 }
1585
1586 // Check if this is a string literal or constant string pointer
1587 if (arg_ty->isPointerTy()) {
1588 // Pointer to just one type
1589 assert(arg_ty->getNumContainedTypes() == 1);
1590
1591 lldb::addr_t addr = tmp_op.ULongLong();
1592 size_t dataSize = 0;
1593
David Blaikiea322f362017-01-06 00:38:06 +00001594 bool Success = execution_unit.GetAllocSize(addr, dataSize);
1595 (void)Success;
1596 assert(Success &&
1597 "unable to locate host data for transfer to device");
1598 // Create the required buffer
1599 rawArgs[i].size = dataSize;
1600 rawArgs[i].data_ap.reset(new uint8_t[dataSize + 1]);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001601
David Blaikiea322f362017-01-06 00:38:06 +00001602 // Read string from host memory
1603 execution_unit.ReadMemory(rawArgs[i].data_ap.get(), addr, dataSize,
1604 error);
1605 assert(!error.Fail() &&
1606 "we have failed to read the string from memory");
1607
1608 // Add null terminator
1609 rawArgs[i].data_ap[dataSize] = '\0';
1610 rawArgs[i].type = lldb_private::ABI::CallArgument::HostPointer;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001611 } else /* if ( arg_ty->isPointerTy() ) */
1612 {
1613 rawArgs[i].type = lldb_private::ABI::CallArgument::TargetValue;
1614 // Get argument size in bytes
1615 rawArgs[i].size = arg_ty->getIntegerBitWidth() / 8;
1616 // Push value into argument list for thread plan
1617 rawArgs[i].value = tmp_op.ULongLong();
1618 }
1619 }
1620
1621 // Pack the arguments into an llvm::array
1622 llvm::ArrayRef<lldb_private::ABI::CallArgument> args(rawArgs, numArgs);
1623
1624 // Setup a thread plan to call the target function
1625 lldb::ThreadPlanSP call_plan_sp(
1626 new lldb_private::ThreadPlanCallFunctionUsingABI(
1627 exe_ctx.GetThreadRef(), funcAddr, *prototype, *returnType, args,
1628 options));
1629
1630 // Check if the plan is valid
1631 lldb_private::StreamString ss;
1632 if (!call_plan_sp || !call_plan_sp->ValidatePlan(&ss)) {
1633 error.SetErrorToGenericError();
1634 error.SetErrorStringWithFormat(
1635 "unable to make ThreadPlanCallFunctionUsingABI for 0x%llx",
1636 I.ULongLong());
1637 return false;
1638 }
1639
1640 exe_ctx.GetProcessPtr()->SetRunningUserExpression(true);
1641
1642 // Execute the actual function call thread plan
1643 lldb::ExpressionResults res = exe_ctx.GetProcessRef().RunThreadPlan(
1644 exe_ctx, call_plan_sp, options, diagnostics);
1645
1646 // Check that the thread plan completed successfully
1647 if (res != lldb::ExpressionResults::eExpressionCompleted) {
1648 error.SetErrorToGenericError();
1649 error.SetErrorStringWithFormat("ThreadPlanCallFunctionUsingABI failed");
1650 return false;
1651 }
1652
1653 exe_ctx.GetProcessPtr()->SetRunningUserExpression(false);
1654
1655 // Void return type
1656 if (returnType->isVoidTy()) {
1657 // Cant assign to void types, so we leave the frame untouched
1658 } else
1659 // Integer or pointer return type
1660 if (returnType->isIntegerTy() || returnType->isPointerTy()) {
1661 // Get the encapsulated return value
1662 lldb::ValueObjectSP retVal = call_plan_sp.get()->GetReturnValueObject();
1663
1664 lldb_private::Scalar returnVal = -1;
1665 lldb_private::ValueObject *vobj = retVal.get();
1666
1667 // Check if the return value is valid
1668 if (vobj == nullptr || retVal.empty()) {
1669 error.SetErrorToGenericError();
1670 error.SetErrorStringWithFormat("unable to get the return value");
1671 return false;
1672 }
1673
1674 // Extract the return value as a integer
1675 lldb_private::Value &value = vobj->GetValue();
1676 returnVal = value.GetScalar();
1677
1678 // Push the return value as the result
1679 frame.AssignValue(inst, returnVal, module);
1680 }
1681 } break;
1682 }
1683
1684 ++frame.m_ii;
1685 }
1686
1687 if (num_insts >= 4096) {
1688 error.SetErrorToGenericError();
1689 error.SetErrorString(infinite_loop_error);
1690 return false;
1691 }
1692
1693 return false;
Sean Callanan14cb2aa2013-04-17 18:35:47 +00001694}