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