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