-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDILEval.cpp
More file actions
3316 lines (2931 loc) · 119 KB
/
DILEval.cpp
File metadata and controls
3316 lines (2931 loc) · 119 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
//===-- DILEval.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/ValueObject/DILEval.h"
#include "lldb/Symbol/VariableList.h"
#include "lldb/Target/RegisterContext.h"
#include "lldb/ValueObject/DILAST.h"
#include "lldb/ValueObject/ValueObject.h"
#include "lldb/ValueObject/ValueObjectRegister.h"
#include "lldb/ValueObject/ValueObjectVariable.h"
#include "lldb/lldb-enumerations.h"
#include "llvm/ADT/APSInt.h"
#include "llvm/Support/FormatAdapters.h"
#include "llvm/Support/FormatVariadic.h"
#include <memory>
namespace {
const char *kInvalidOperandsToUnaryExpression =
"invalid argument type {0} to unary expression";
const char *kInvalidOperandsToBinaryExpression =
"invalid operands to binary expression ({0} and {1})";
const char *kValueIsNotConvertibleToBool =
"value of type {0} is not contextually convertible to 'bool'";
} // namespace
namespace lldb_private::dil {
llvm::Error Interpreter::BailOut(ErrorCode code, const std::string &message,
uint32_t loc) {
Status error = Status((uint32_t)code, lldb::eErrorTypeGeneric,
FormatDiagnostics(m_expr, message, loc));
return error.ToError();
}
lldb::ValueObjectSP
GetDynamicOrSyntheticValue(lldb::ValueObjectSP in_valobj_sp,
lldb::DynamicValueType use_dynamic,
bool use_synthetic) {
Status error;
if (!in_valobj_sp) {
error = Status("invalid value object");
return in_valobj_sp;
}
lldb::ValueObjectSP value_sp = in_valobj_sp;
Target *target = value_sp->GetTargetSP().get();
// If this ValueObject holds an error, then it is valuable for that.
if (value_sp->GetError().Fail())
return value_sp;
if (!target)
return lldb::ValueObjectSP();
if (use_dynamic != lldb::eNoDynamicValues) {
lldb::ValueObjectSP dynamic_sp = value_sp->GetDynamicValue(use_dynamic);
if (dynamic_sp)
value_sp = dynamic_sp;
}
if (use_synthetic) {
lldb::ValueObjectSP synthetic_sp = value_sp->GetSyntheticValue();
if (synthetic_sp)
value_sp = synthetic_sp;
}
if (!value_sp)
error = Status("invalid value object");
return value_sp;
}
template <typename T> bool Compare(BinaryOpKind kind, const T &l, const T &r) {
switch (kind) {
case BinaryOpKind::EQ:
return l == r;
case BinaryOpKind::NE:
return l != r;
case BinaryOpKind::LT:
return l < r;
case BinaryOpKind::LE:
return l <= r;
case BinaryOpKind::GT:
return l > r;
case BinaryOpKind::GE:
return l >= r;
default:
assert(false && "invalid ast: invalid comparison operation");
return false;
}
}
static uint64_t GetUInt64(lldb::ValueObjectSP value_sp) {
// GetValueAsUnsigned performs overflow according to the underlying type.
// For example, if the underlying type is `int32_t` and the value is `-1`,
// GetValueAsUnsigned will return 4294967295.
return value_sp->GetCompilerType().IsSigned()
? value_sp->GetValueAsSigned(0)
: value_sp->GetValueAsUnsigned(0);
}
static lldb::ValueObjectSP EvaluateArithmeticOpInteger(lldb::TargetSP target,
BinaryOpKind kind,
lldb::ValueObjectSP lhs,
lldb::ValueObjectSP rhs,
CompilerType rtype)
{
assert(lhs->GetCompilerType().IsInteger() &&
rhs->GetCompilerType().IsInteger() &&
"invalid ast: both operands must be integers");
assert((kind == BinaryOpKind::Shl || kind == BinaryOpKind::Shr ||
lhs->GetCompilerType().CompareTypes(rhs->GetCompilerType())) &&
"invalid ast: operands must have the same type");
auto wrap = [target, rtype](auto value) {
return ValueObject::CreateValueObjectFromAPInt(target, value, rtype,
"result");
};
llvm::Expected<llvm::APSInt> l_value = lhs->GetValueAsAPSInt();
llvm::Expected<llvm::APSInt> r_value = rhs->GetValueAsAPSInt();
if (l_value && r_value) {
llvm::APSInt l = *l_value;
llvm::APSInt r = *r_value;
switch (kind) {
case BinaryOpKind::Add:
return wrap(l + r);
case BinaryOpKind::Sub:
return wrap(l - r);
case BinaryOpKind::Div:
return wrap(l / r);
case BinaryOpKind::Mul:
return wrap(l * r);
case BinaryOpKind::Rem:
return wrap(l % r);
case BinaryOpKind::And:
return wrap(l & r);
case BinaryOpKind::Or:
return wrap(l | r);
case BinaryOpKind::Xor:
return wrap(l ^ r);
case BinaryOpKind::Shl:
return wrap(l.shl(r));
case BinaryOpKind::Shr:
// Apply arithmetic shift on signed values and logical shift operation
// on unsigned values.
return wrap(l.isSigned() ? l.ashr(r) : l.lshr(r));
default:
assert(false && "invalid ast: invalid arithmetic operation");
return lldb::ValueObjectSP();
}
} else {
return lldb::ValueObjectSP();
}
}
static lldb::ValueObjectSP EvaluateArithmeticOpFloat(lldb::TargetSP target,
BinaryOpKind kind,
lldb::ValueObjectSP lhs,
lldb::ValueObjectSP rhs,
CompilerType rtype) {
assert((lhs->GetCompilerType().IsFloat() &&
lhs->GetCompilerType().CompareTypes(rhs->GetCompilerType())) &&
"invalid ast: operands must be floats and have the same type");
auto wrap = [target, rtype](auto value) {
return ValueObject::CreateValueObjectFromAPFloat(target, value, rtype, "result");
};
auto lval_or_err = lhs->GetValueAsAPFloat();
auto rval_or_err = rhs->GetValueAsAPFloat();
if (lval_or_err && rval_or_err) {
llvm::APFloat l = *lval_or_err;
llvm::APFloat r = *rval_or_err;
switch (kind) {
case BinaryOpKind::Add:
return wrap(l + r);
case BinaryOpKind::Sub:
return wrap(l - r);
case BinaryOpKind::Div:
return wrap(l / r);
case BinaryOpKind::Mul:
return wrap(l * r);
default:
assert(false && "invalid ast: invalid arithmetic operation");
return lldb::ValueObjectSP();
}
}
return lldb::ValueObjectSP();
}
static lldb::ValueObjectSP EvaluateArithmeticOp(lldb::TargetSP target,
BinaryOpKind kind,
lldb::ValueObjectSP lhs,
lldb::ValueObjectSP rhs,
CompilerType rtype) {
assert((rtype.IsInteger() || rtype.IsFloat()) &&
"invalid ast: result type must either integer or floating point");
// Evaluate arithmetic operation for two integral values.
if (rtype.IsInteger()) {
return EvaluateArithmeticOpInteger(target, kind, lhs, rhs, rtype);
}
// Evaluate arithmetic operation for two floating point values.
if (rtype.IsFloat()) {
return EvaluateArithmeticOpFloat(target, kind, lhs, rhs, rtype);
}
return lldb::ValueObjectSP();
}
static bool IsInvalidDivisionByMinusOne(lldb::ValueObjectSP lhs_sp,
lldb::ValueObjectSP rhs_sp)
{
assert(lhs_sp->GetCompilerType().IsInteger() &&
rhs_sp->GetCompilerType().IsInteger() && "operands should be integers");
// The result type should be signed integer.
auto basic_type =
rhs_sp->GetCompilerType().GetCanonicalType().GetBasicTypeEnumeration();
if (basic_type != lldb::eBasicTypeInt && basic_type != lldb::eBasicTypeLong &&
basic_type != lldb::eBasicTypeLongLong) {
return false;
}
// The RHS should be equal to -1.
if (rhs_sp->GetValueAsSigned(0) != -1) {
return false;
}
// The LHS should be equal to the minimum value the result type can hold.
uint64_t byte_size = 0;
if (auto temp = rhs_sp->GetCompilerType().GetByteSize(rhs_sp->GetTargetSP().get()))
byte_size = temp.value();
auto bit_size = byte_size * CHAR_BIT;
return lhs_sp->GetValueAsSigned(0) + (1LLU << (bit_size - 1)) == 0;
}
Status SetUbStatus(ErrorCode code) {
llvm::StringRef err_str;
switch ((int) code) {
case (int) ErrorCode::kUBDivisionByZero:
err_str ="Error: Division by zero detected.";
break;
case (int) ErrorCode::kUBDivisionByMinusOne:
// If "a / b" isn't representable in its result type, then results of
// "a / b" and "a % b" are undefined behaviour. This happens when "a"
// is equal to the minimum value of the result type and "b" is equal
// to -1.
err_str ="Error: Invalid division by negative one detected.";
break;
case (int) ErrorCode::kUBInvalidCast:
err_str ="Error: Invalid type cast detected.";
break;
case (int) ErrorCode::kUBInvalidShift:
err_str ="Error: Invalid shift detected.";
break;
case (int) ErrorCode::kUBNullPtrArithmetic:
err_str ="Error: Attempt to perform arithmetic with null ptr detected.";
break;
case (int) ErrorCode::kUBInvalidPtrDiff:
err_str ="Error: Attempt to perform invalid ptr arithmetic detected.";
break;
default:
err_str ="Error: Unknown undefined behavior error.";
break;
}
return Status(err_str.str());
}
static lldb::ValueObjectSP LookupStaticIdentifier(
VariableList &variable_list, std::shared_ptr<StackFrame> exe_scope,
llvm::StringRef name_ref, llvm::StringRef unqualified_name) {
// First look for an exact match (to the possibly qualified name)
for (const lldb::VariableSP &var_sp : variable_list) {
lldb::ValueObjectSP valobj_sp(
ValueObjectVariable::Create(exe_scope.get(), var_sp));
if (valobj_sp && valobj_sp->GetVariable() &&
(valobj_sp->GetVariable()->NameMatches(ConstString(name_ref))))
return valobj_sp;
}
// If the qualified name is the same as the unqualified name there's nothing
// more to be done.
if (name_ref == unqualified_name)
return nullptr;
// We didn't match the qualified name; try to match the unqualified name.
for (const lldb::VariableSP &var_sp : variable_list) {
lldb::ValueObjectSP valobj_sp(
ValueObjectVariable::Create(exe_scope.get(), var_sp));
if (valobj_sp && valobj_sp->GetVariable() &&
(valobj_sp->GetVariable()->NameMatches(ConstString(unqualified_name))))
return valobj_sp;
}
return nullptr;
}
struct EnumMember {
CompilerType type;
ConstString name;
llvm::APSInt value;
};
static std::vector<EnumMember> GetEnumMembers(CompilerType type) {
std::vector<EnumMember> enum_member_list;
if (type.IsValid()) {
type.ForEachEnumerator(
[&enum_member_list](const CompilerType &integer_type, ConstString name,
const llvm::APSInt &value) -> bool {
EnumMember enum_member = {integer_type, name, value};
enum_member_list.push_back(enum_member);
return true; // Keep iterating
});
}
return enum_member_list;
}
CompilerType
ResolveTypeByName(const std::string &name,
std::shared_ptr<ExecutionContextScope> ctx_scope) {
// Internally types don't have global scope qualifier in their names and
// LLDB doesn't support queries with it too.
llvm::StringRef name_ref(name);
if (name_ref.starts_with("::"))
name_ref = name_ref.drop_front(2);
std::vector<CompilerType> result_type_list;
lldb::TargetSP target_sp = ctx_scope->CalculateTarget();
const char *type_name = name_ref.data();
if (type_name && type_name[0] && target_sp) {
ModuleList &images = target_sp->GetImages();
ConstString const_type_name(type_name);
TypeQuery query(type_name);
TypeResults results;
images.FindTypes(nullptr, query, results);
for (const lldb::TypeSP &type_sp : results.GetTypeMap().Types())
if (type_sp)
result_type_list.push_back(type_sp->GetFullCompilerType());
if (auto process_sp = target_sp->GetProcessSP()) {
for (auto *runtime : process_sp->GetLanguageRuntimes()) {
if (auto *vendor = runtime->GetDeclVendor()) {
auto types = vendor->FindTypes(const_type_name, UINT32_MAX);
for (auto type : types)
result_type_list.push_back(type);
}
}
}
if (result_type_list.empty()) {
for (auto type_system_sp : target_sp->GetScratchTypeSystems())
if (auto compiler_type =
type_system_sp->GetBuiltinTypeByName(const_type_name))
result_type_list.push_back(compiler_type);
}
}
// We've found multiple types, try finding the "correct" one.
CompilerType full_match;
std::vector<CompilerType> partial_matches;
for (uint32_t i = 0; i < result_type_list.size(); ++i) {
CompilerType type = result_type_list[i];
llvm::StringRef type_name_ref = type.GetTypeName().GetStringRef();
;
if (type_name_ref == name_ref)
full_match = type;
else if (type_name_ref.ends_with(name_ref))
partial_matches.push_back(type);
}
// Full match is always correct.
if (full_match.IsValid())
return full_match;
// If we have partial matches, pick a "random" one.
if (partial_matches.size() > 0)
return partial_matches.back();
return {};
}
static lldb::VariableSP DILFindVariable(ConstString name,
lldb::VariableListSP variable_list) {
lldb::VariableSP exact_match;
std::vector<lldb::VariableSP> possible_matches;
for (lldb::VariableSP var_sp : *variable_list) {
llvm::StringRef str_ref_name = var_sp->GetName().GetStringRef();
// Check for global vars, which might start with '::'.
str_ref_name.consume_front("::");
if (str_ref_name == name.GetStringRef())
possible_matches.push_back(var_sp);
else if (var_sp->NameMatches(name))
possible_matches.push_back(var_sp);
}
// Look for exact matches (favors local vars over global vars)
auto exact_match_it =
llvm::find_if(possible_matches, [&](lldb::VariableSP var_sp) {
return var_sp->GetName() == name;
});
if (exact_match_it != possible_matches.end())
return *exact_match_it;
// Look for a global var exact match.
for (auto var_sp : possible_matches) {
llvm::StringRef str_ref_name = var_sp->GetName().GetStringRef();
str_ref_name.consume_front("::");
if (str_ref_name == name.GetStringRef())
return var_sp;
}
// If there's a single non-exact match, take it.
if (possible_matches.size() == 1)
return possible_matches[0];
return nullptr;
}
lldb::ValueObjectSP LookupGlobalIdentifier(
llvm::StringRef name_ref, std::shared_ptr<StackFrame> stack_frame,
lldb::TargetSP target_sp, lldb::DynamicValueType use_dynamic,
CompilerType *scope_ptr) {
// First look for match in "local" global variables
lldb::VariableListSP variable_list(stack_frame->GetInScopeVariableList(true));
name_ref.consume_front("::");
lldb::ValueObjectSP value_sp;
if (variable_list) {
lldb::VariableSP var_sp =
DILFindVariable(ConstString(name_ref), variable_list);
if (var_sp)
value_sp =
stack_frame->GetValueObjectForFrameVariable(var_sp, use_dynamic);
}
if (value_sp)
return value_sp;
// Also check for static global vars.
if (variable_list) {
const char *type_name = "";
if (scope_ptr)
type_name = scope_ptr->GetCanonicalType().GetTypeName().AsCString();
std::string name_with_type_prefix =
llvm::formatv("{0}::{1}", type_name, name_ref).str();
value_sp = LookupStaticIdentifier(*variable_list, stack_frame,
name_with_type_prefix, name_ref);
if (!value_sp)
value_sp = LookupStaticIdentifier(*variable_list, stack_frame, name_ref,
name_ref);
}
if (value_sp)
return value_sp;
// Check for match in modules global variables.
VariableList modules_var_list;
target_sp->GetImages().FindGlobalVariables(
ConstString(name_ref), std::numeric_limits<uint32_t>::max(),
modules_var_list);
if (modules_var_list.Empty())
return nullptr;
for (const lldb::VariableSP &var_sp : modules_var_list) {
std::string qualified_name = llvm::formatv("::{0}", name_ref).str();
if (var_sp->NameMatches(ConstString(name_ref)) ||
var_sp->NameMatches(ConstString(qualified_name))) {
value_sp = ValueObjectVariable::Create(stack_frame.get(), var_sp);
break;
}
}
if (value_sp)
return value_sp;
return nullptr;
}
lldb::ValueObjectSP LookupIdentifier(llvm::StringRef name_ref,
std::shared_ptr<StackFrame> stack_frame,
lldb::DynamicValueType use_dynamic,
CompilerType *scope_ptr) {
lldb::ValueObjectSP value_sp;
// Support $rax as a special syntax for accessing registers.
// Will return an invalid value in case the requested register doesn't exist.
if (name_ref.consume_front("$")) {
lldb::RegisterContextSP reg_ctx(stack_frame->GetRegisterContext());
if (!reg_ctx)
return nullptr;
if (const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoByName(name_ref))
value_sp =
ValueObjectRegister::Create(stack_frame.get(), reg_ctx, reg_info);
if (value_sp)
return value_sp;
return nullptr;
}
lldb::VariableListSP variable_list(
stack_frame->GetInScopeVariableList(false));
if (!name_ref.contains("::")) {
if (!scope_ptr || !scope_ptr->IsValid()) {
// Lookup in the current frame.
// Try looking for a local variable in current scope.
if (variable_list) {
lldb::VariableSP var_sp =
DILFindVariable(ConstString(name_ref), variable_list);
if (var_sp)
value_sp =
stack_frame->GetValueObjectForFrameVariable(var_sp, use_dynamic);
}
if (!value_sp)
value_sp = stack_frame->FindVariable(ConstString(name_ref));
if (value_sp)
return value_sp;
// Try looking for an instance variable (class member).
SymbolContext sc = stack_frame->GetSymbolContext(
lldb::eSymbolContextFunction | lldb::eSymbolContextBlock);
llvm::StringRef ivar_name = sc.GetInstanceVariableName();
value_sp = stack_frame->FindVariable(ConstString(ivar_name));
if (value_sp)
value_sp = value_sp->GetChildMemberWithName(name_ref);
if (value_sp)
return value_sp;
}
}
// Try looking up enum value.
if (!value_sp && name_ref.contains("::")) {
auto [enum_typename, enumerator_name] = name_ref.rsplit("::");
auto type = ResolveTypeByName(enum_typename.str(), stack_frame);
std::vector<EnumMember> enum_members = GetEnumMembers(type);
for (size_t i = 0; i < enum_members.size(); i++) {
EnumMember enum_member = enum_members[i];
if (enum_member.name == enumerator_name) {
uint64_t bytes = enum_member.value.getZExtValue();
uint64_t byte_size = 0;
if (auto temp = type.GetByteSize(stack_frame.get()))
byte_size = temp.value();
lldb::TargetSP target_sp = stack_frame->CalculateTarget();
lldb::DataExtractorSP data_sp = std::make_shared<DataExtractor>(
&bytes, byte_size, target_sp->GetArchitecture().GetByteOrder(),
static_cast<uint8_t>(
target_sp->GetArchitecture().GetAddressByteSize()));
ExecutionContext exe_ctx(
ExecutionContextRef(ExecutionContext(target_sp.get(), false)));
value_sp = ValueObject::CreateValueObjectFromData("result", *data_sp,
exe_ctx, type);
break;
}
}
}
if (value_sp)
return value_sp;
return nullptr;
}
Interpreter::Interpreter(lldb::TargetSP target, llvm::StringRef expr,
lldb::DynamicValueType use_dynamic,
std::shared_ptr<StackFrame> frame_sp)
: m_target(std::move(target)), m_expr(expr), m_default_dynamic(use_dynamic),
m_exe_ctx_scope(frame_sp) {}
void Interpreter::SetContextVars(
std::unordered_map<std::string, lldb::ValueObjectSP> context_vars) {
m_context_vars = std::move(context_vars);
}
llvm::Expected<lldb::ValueObjectSP>
Interpreter::DILEval(const ASTNode *tree, lldb::TargetSP target_sp) {
// Evaluate an AST.
auto value_or_error = DILEvalNode(tree);
// Return the computed result-or-error.
return value_or_error;
}
llvm::Expected<lldb::ValueObjectSP>
Interpreter::DILEvalNode(const ASTNode *node, FlowAnalysis *flow) {
// Set up the evaluation context for the current node.
m_flow_analysis_chain.push_back(flow);
// Traverse an AST pointed by the `node`.
auto value_or_error = node->Accept(this);
// Cleanup the context.
m_flow_analysis_chain.pop_back();
// Return the computed value-or-error. The caller is responsible for
// checking if an error occured during the evaluation.
return value_or_error;
}
lldb::ValueObjectSP
Interpreter::EvaluateMemberOf(lldb::ValueObjectSP value,
const std::vector<uint32_t> &path,
bool use_synthetic, bool is_dynamic) {
// The given `value` can be a pointer, but GetChildAtIndex works for pointers
// too, so we don't need to dereference it explicitely. This also avoid having
// an "ephemeral" parent lldb::ValueObjectSP, representing the dereferenced
// value.
lldb::ValueObjectSP member_val_sp = value;
lldb::DynamicValueType use_dynamic =
(!is_dynamic) ? lldb::eNoDynamicValues : lldb::eDynamicDontRunTarget;
for (uint32_t idx : path) {
member_val_sp = member_val_sp->GetChildAtIndex(idx, /*can_create*/ true);
}
if (!member_val_sp && is_dynamic) {
lldb::ValueObjectSP dyn_val_sp = value->GetDynamicValue(use_dynamic);
if (dyn_val_sp) {
for (uint32_t idx : path) {
dyn_val_sp = dyn_val_sp->GetChildAtIndex(idx, true);
}
member_val_sp = dyn_val_sp;
}
}
assert(member_val_sp && "invalid ast: invalid member access");
// If value is a reference, derefernce it to get to the underlying type. All
// operations on a reference should be actually operations on the referent.
Status error;
if (member_val_sp->GetCompilerType().IsReferenceType()) {
member_val_sp = member_val_sp->Dereference(error);
assert(member_val_sp && error.Success() &&
"unable to dereference member val");
}
return member_val_sp;
}
llvm::Expected<lldb::ValueObjectSP>
Interpreter::Visit(const ScalarLiteralNode *node) {
CompilerType result_type = node->result_type();
Scalar value = node->GetValue();
if (result_type.IsBoolean()) {
unsigned int int_val = value.UInt();
bool b_val = false;
if (int_val == 1)
b_val = true;
return ValueObject::CreateValueObjectFromBool(m_target, b_val, "result");
}
if (result_type.IsFloat()) {
llvm::APFloat val = value.GetAPFloat();
return ValueObject::CreateValueObjectFromAPFloat(m_target, val, result_type,
"result");
}
if (result_type.IsInteger() || result_type.IsNullPtrType() ||
result_type.IsPointerType()) {
llvm::APInt val = value.GetAPSInt();
return ValueObject::CreateValueObjectFromAPInt(m_target, val, result_type,
"result");
}
return lldb::ValueObjectSP();
}
llvm::Expected<lldb::ValueObjectSP>
Interpreter::Visit(const StringLiteralNode *node) {
CompilerType result_type = node->result_type();
std::string val = node->GetValue();
ExecutionContext exe_ctx(m_target.get(), false);
uint64_t byte_size = 0;
if (auto temp = result_type.GetByteSize(m_target.get()))
byte_size = temp.value();
lldb::DataExtractorSP data_sp = std::make_shared<DataExtractor>(
reinterpret_cast<const void*>(val.data()), byte_size,
exe_ctx.GetByteOrder(), exe_ctx.GetAddressByteSize());
return ValueObject::CreateValueObjectFromData("result", *data_sp, exe_ctx,
result_type);
}
llvm::Expected<lldb::ValueObjectSP>
Interpreter::Visit(const IdentifierNode *node) {
lldb::DynamicValueType use_dynamic = node->GetUseDynamic();
lldb::ValueObjectSP identifier =
LookupIdentifier(node->GetName(), m_exe_ctx_scope, use_dynamic);
if (!identifier)
identifier = LookupGlobalIdentifier(node->GetName(), m_exe_ctx_scope,
m_target, use_dynamic);
if (!identifier) {
std::string errMsg =
llvm::formatv("use of undeclared identifier '{0}'", node->GetName());
Status error = Status(
(uint32_t)ErrorCode::kUndeclaredIdentifier, lldb::eErrorTypeGeneric,
FormatDiagnostics(m_expr, errMsg, node->GetLocation()));
return error.ToError();
}
if (identifier->GetCompilerType().IsReferenceType()) {
Status error;
identifier = identifier->Dereference(error);
if (error.Fail())
return error.ToError();
}
return identifier;
}
llvm::Expected<lldb::ValueObjectSP> Interpreter::Visit(const SizeOfNode *node) {
auto operand = node->operand();
uint64_t deref_byte_size = 0;
uint64_t other_byte_size = 0;
if (auto temp = operand.GetNonReferenceType().GetByteSize(m_target.get()))
deref_byte_size = temp.value();
if (auto temp = operand.GetByteSize(m_target.get()))
other_byte_size = temp.value();
// For reference type (int&) we need to look at the referenced type.
size_t size = operand.IsReferenceType()
? deref_byte_size
: other_byte_size;
CompilerType type = node->GetDereferencedResultType();
ExecutionContext exe_ctx(m_target.get(), false);
uint64_t byte_size = 0;
if (auto temp = type.GetByteSize(m_target.get()))
byte_size = temp.value();
lldb::DataExtractorSP data_sp = std::make_shared<DataExtractor>(
reinterpret_cast<const void*>(&size), byte_size,
exe_ctx.GetByteOrder(), exe_ctx.GetAddressByteSize());
return ValueObject::CreateValueObjectFromData("result", *data_sp, exe_ctx,
type);
}
llvm::Expected<lldb::ValueObjectSP>
Interpreter::Visit(const BuiltinFunctionCallNode *node) {
if (node->name() == "__log2") {
assert(node->arguments().size() == 1 &&
"invalid ast: expected exactly one argument to `__log2`");
// Get the first (and the only) argument and evaluate it.
auto &arg = node->arguments()[0];
auto val_or_err = DILEvalNode(arg.get());
if (!val_or_err) {
return val_or_err;
}
lldb::ValueObjectSP val = *val_or_err;
assert(val->GetCompilerType().IsInteger() &&
"invalid ast: argument to __log2 must be an interger");
// Use Log2_32 to match the behaviour of Visual Studio debugger.
uint32_t ret =
llvm::Log2_32(static_cast<uint32_t>(val->GetValueAsUnsigned(0)));
CompilerType target_type;
for (auto type_system_sp : m_target->GetScratchTypeSystems())
if (auto compiler_type =
type_system_sp->GetBasicTypeFromAST(lldb::eBasicTypeUnsignedInt)) {
target_type = compiler_type;
break;
}
ExecutionContext exe_ctx(m_target.get(), false);
uint64_t byte_size = 0;
if (auto temp = target_type.GetByteSize(m_target.get()))
byte_size = temp.value();
lldb::DataExtractorSP data_sp = std::make_shared<DataExtractor>(
reinterpret_cast<const void*>(&ret), byte_size,
exe_ctx.GetByteOrder(), exe_ctx.GetAddressByteSize());
return ValueObject::CreateValueObjectFromData("result", *data_sp, exe_ctx,
target_type);
}
if (node->name() == "__findnonnull") {
assert(node->arguments().size() == 2 &&
"invalid ast: expected exactly two arguments to `__findnonnull`");
auto &arg1 = node->arguments()[0];
auto val_or_err = DILEvalNode(arg1.get());
if (!val_or_err) {
return val_or_err;
}
lldb::ValueObjectSP val1_sp = *val_or_err;
// Resolve data address for the first argument.
uint64_t addr;
if (val1_sp->GetCompilerType().IsPointerType()) {
addr = val1_sp->GetValueAsUnsigned(0);
} else if (val1_sp->GetCompilerType().IsArrayType()) {
addr = val1_sp->GetLoadAddress();
} else {
Status error = Status(
(uint32_t)ErrorCode::kInvalidOperandType, lldb::eErrorTypeGeneric,
FormatDiagnostics(
m_expr,
llvm::formatv("no known conversion from '{0}' to 'T*' for 1st "
"argument of __findnonnull()",
val1_sp->GetCompilerType().GetTypeName()),
arg1->GetLocation()));
return error.ToError();
}
auto &arg2 = node->arguments()[1];
auto val2_or_err = DILEvalNode(arg2.get());
if (!val2_or_err) {
return val2_or_err;
}
lldb::ValueObjectSP val2_sp = *val2_or_err;
int64_t size = val2_sp->GetValueAsSigned(0);
if (size < 0 || size > 100000000) {
Status error = Status(
(uint32_t)ErrorCode::kInvalidOperandType, lldb::eErrorTypeGeneric,
FormatDiagnostics(
m_expr,
llvm::formatv(
"passing in a buffer size ('{0}') that is negative or in "
"excess of 100 million to __findnonnull() is not allowed.",
size),
arg2->GetLocation()));
return error.ToError();
}
lldb::ProcessSP process = m_target->GetProcessSP();
size_t ptr_size = m_target->GetArchitecture().GetAddressByteSize();
uint64_t memory = 0;
Status error;
CompilerType target_type;
for (auto type_system_sp : m_target->GetScratchTypeSystems())
if (auto compiler_type =
type_system_sp->GetBasicTypeFromAST(lldb::eBasicTypeInt)) {
target_type = compiler_type;
break;
}
ExecutionContext exe_ctx(m_target.get(), false);
uint64_t byte_size = 0;
if (auto temp = target_type.GetByteSize(m_target.get()))
byte_size = temp.value();
for (int i = 0; i < size; ++i) {
size_t read =
process->ReadMemory(addr + i * ptr_size, &memory, ptr_size, error);
if (error.Fail() || read != ptr_size) {
const char *message = error.AsCString();
Status error =
Status((uint32_t)ErrorCode::kUnknown, lldb::eErrorTypeGeneric,
FormatDiagnostics(
m_expr,
llvm::formatv("error calling __findnonnull(): {0}",
message ? message : "cannot read memory"),
node->GetLocation()));
return error.ToError();
}
if (memory != 0) {
lldb::DataExtractorSP data_sp = std::make_shared<DataExtractor>(
reinterpret_cast<const void*>(&i), byte_size,
exe_ctx.GetByteOrder(), exe_ctx.GetAddressByteSize());
return ValueObject::CreateValueObjectFromData("result", *data_sp,
exe_ctx, target_type);
}
}
int ret = -1;
lldb::DataExtractorSP data_sp = std::make_shared<DataExtractor>(
reinterpret_cast<const void*>(&ret), byte_size,
exe_ctx.GetByteOrder(), exe_ctx.GetAddressByteSize());
return ValueObject::CreateValueObjectFromData("result", *data_sp, exe_ctx,
target_type);
}
Status error("invalid ast: unknown builtin function");
return error.ToError();
}
llvm::Expected<lldb::ValueObjectSP>
Interpreter::Visit(const CStyleCastNode *node) {
// Get the type and the value we need to cast.
auto type = node->type();
auto rhs_or_err = DILEvalNode(node->operand());
if (!rhs_or_err) {
return rhs_or_err;
}
lldb::ValueObjectSP rhs = *rhs_or_err;
if (rhs->GetCompilerType().IsReferenceType()) {
Status error;
rhs = rhs->Dereference(error);
if (error.Fail())
return error.ToError();
}
switch (node->cast_kind()) {
case CStyleCastKind::eEnumeration: {
assert(type.IsEnumerationType() &&
"invalid ast: target type should be an enumeration.");
if (rhs->GetCompilerType().IsFloat())
return rhs->CastToEnumType(type);
if (rhs->GetCompilerType().IsInteger() ||
rhs->GetCompilerType().IsEnumerationType())
return rhs->CastToEnumType(type);
Status error(
"invalid ast: operand is not convertible to enumeration type");
return error.ToError();
}
case CStyleCastKind::eNullptr: {
assert(
(type.GetCanonicalType().GetBasicTypeEnumeration() ==
lldb::eBasicTypeNullPtr)
&& "invalid ast: target type should be a nullptr_t.");
return ValueObject::CreateValueObjectFromNullptr(m_target, type,
"result");
}
case CStyleCastKind::eReference: {
lldb::ValueObjectSP rhs_sp(GetDynamicOrSyntheticValue(rhs));
return lldb::ValueObjectSP(rhs_sp->Cast(type.GetNonReferenceType()));
}
case CStyleCastKind::eNone: {
switch (node->promo_kind()) {
case TypePromotionCastKind::eArithmetic: {
assert((type.GetCanonicalType().GetBasicTypeEnumeration() !=
lldb::eBasicTypeInvalid) &&
"invalid ast: target type should be a basic type.");
// Pick an appropriate cast.
if (rhs->GetCompilerType().IsPointerType()
|| rhs->GetCompilerType().IsNullPtrType()) {
return rhs->CastToBasicType(type);
}
if (rhs->GetCompilerType().IsScalarType()) {
return rhs->CastToBasicType(type);
}
if (rhs->GetCompilerType().IsEnumerationType()) {
return rhs->CastToBasicType(type);
}
Status error(
"invalid ast: operand is not convertible to arithmetic type");
return error.ToError();
}
case TypePromotionCastKind::ePointer: {
assert(type.IsPointerType() &&
"invalid ast: target type should be a pointer.");
uint64_t addr = rhs->GetCompilerType().IsArrayType()
? rhs->GetLoadAddress()
: GetUInt64(rhs);
llvm::StringRef name = "result";
ExecutionContext exe_ctx(m_target.get(), false);
return ValueObject::CreateValueObjectFromAddress(
name, addr, exe_ctx, type,
/* do_deref */ false);
}
case TypePromotionCastKind::eNone:
return lldb::ValueObjectSP();
}
}
}
Status error("invalid ast: unexpected c-style cast kind");
return error.ToError();
}
llvm::Expected<lldb::ValueObjectSP>
Interpreter::Visit(const CxxStaticCastNode *node) {
// Get the type and the value we need to cast.
auto type = node->type();
auto orig_type = node->orig_type();
auto rhs_or_err = DILEvalNode(node->operand());
if (!rhs_or_err) {
return rhs_or_err;
}
lldb::ValueObjectSP rhs = *rhs_or_err;
if (rhs->GetCompilerType().IsReferenceType()) {