-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathOperationStmt.cpp
More file actions
4503 lines (4015 loc) · 195 KB
/
Copy pathOperationStmt.cpp
File metadata and controls
4503 lines (4015 loc) · 195 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
/*
* Copyright (c) 2024, Trail of Bits, Inc.
*
* This source code is licensed in accordance with the terms specified in
* the LICENSE file found in the root directory of this source tree.
*/
#include <algorithm>
#include <optional>
#include <string>
#include <utility>
#include <clang/AST/ASTContext.h>
#include <clang/AST/Attr.h>
#include <clang/AST/Decl.h>
#include <clang/AST/DeclAccessPair.h>
#include <clang/AST/Expr.h>
#include <clang/AST/NestedNameSpecifier.h>
#include <clang/AST/OperationKinds.h>
#include <clang/AST/RecordLayout.h>
#include <clang/AST/Stmt.h>
#include <clang/AST/Type.h>
#include <clang/Basic/Builtins.h>
#include <clang/Basic/LLVM.h>
#include <clang/Basic/LangOptions.h>
#include <clang/Basic/SourceLocation.h>
#include <clang/Basic/Specifiers.h>
#include <clang/Sema/Lookup.h>
#include <clang/Sema/Sema.h>
#include <llvm/ADT/APInt.h>
#include <llvm/ADT/ArrayRef.h>
#include <llvm/ADT/SmallVector.h>
#include <llvm/Support/Casting.h>
#include <patchestry/AST/ASTConsumer.hpp>
#include <patchestry/AST/FunctionBuilder.hpp>
#include <patchestry/AST/IntrinsicHandlers.hpp>
#include <patchestry/AST/OperationBuilder.hpp>
#include <patchestry/AST/TypeBuilder.hpp>
#include <patchestry/AST/Utils.hpp>
#include <patchestry/Ghidra/Pcode.hpp>
#include <patchestry/Ghidra/PcodeOperations.hpp>
#include <patchestry/Util/Log.hpp>
namespace patchestry::ast {
extern std::optional< Operation >
operationFromKey(const Function &function, const std::string &lookup_key); // NOLINT
namespace {
// Simplify *(&expr) → expr. When PTRADD produces &base[index] and
// STORE/LOAD dereferences it, this cancels the redundant &/* pair so the
// output reads base[index] instead of *(&base[index]).
clang::Expr *simplify_deref_addrof(clang::Expr *expr) {
if (auto *uo = clang::dyn_cast< clang::UnaryOperator >(expr)) {
if (uo->getOpcode() == clang::UO_AddrOf) {
return uo->getSubExpr();
}
}
return nullptr;
}
clang::VarDecl *create_variable_decl( // NOLINT
clang::ASTContext &ctx, clang::DeclContext *dc, const std::string &name,
clang::QualType type, clang::SourceLocation loc
) {
auto *vd = clang::VarDecl::Create(
ctx, dc, loc, loc, &ctx.Idents.get(name), type,
ctx.getTrivialTypeSourceInfo(type), clang::SC_None
);
// CIRGen asserts every VarDecl referenced by a DeclRefExpr is
// marked used. Patchestry bypasses Sema, so we mark it here.
vd->setIsUsed();
return vd;
}
clang::DeclStmt *create_decl_stmt( // NOLINT
clang::ASTContext &ctx, clang::Decl *decl, clang::SourceLocation loc
) {
auto decl_group = clang::DeclGroupRef(decl);
return new (ctx) clang::DeclStmt(decl_group, loc, loc);
}
clang::Expr *createDefaultArgument(clang::ASTContext &ctx, clang::ParmVarDecl *param) {
if (param == nullptr) {
return nullptr;
}
auto param_type = param->getType();
if (param_type->isIntegerType()) {
// param_type may be _Bool/enum (crash StmtPrinter).
return MakeIntLiteralPrintable(
ctx, 0, param_type, param_type->isSignedIntegerType(),
VirtualLoc(ctx)
);
} else if (param_type->isFloatingType()) {
llvm::APFloat value(llvm::APFloat::IEEEsingle(), "0.0");
return clang::FloatingLiteral::Create(
ctx, value, false, param_type, VirtualLoc(ctx)
);
} else if (param_type->isPointerType()) {
// IntegerLiteral asserts on non-integer types; emit (T*)0 as
// CK_NullToPointer over an int-typed 0 instead. #226.
auto *zero = new (ctx) clang::IntegerLiteral(
ctx, llvm::APInt(ctx.getIntWidth(ctx.IntTy), 0), ctx.IntTy,
VirtualLoc(ctx)
);
return clang::ImplicitCastExpr::Create(
ctx, param_type, clang::CK_NullToPointer, zero,
/*BasePath=*/nullptr, clang::VK_PRValue,
clang::FPOptionsOverride()
);
} else if (param_type->isBooleanType()) {
return new (ctx)
clang::CXXBoolLiteralExpr(true, param_type, VirtualLoc(ctx));
} else if (param_type->isEnumeralType()) {
// IntegerLiteral asserts on non-integer types; emit (E)0 as an
// integral cast over an int-typed 0.
auto *zero = new (ctx) clang::IntegerLiteral(
ctx, llvm::APInt(ctx.getIntWidth(ctx.IntTy), 0), ctx.IntTy,
VirtualLoc(ctx)
);
return clang::ImplicitCastExpr::Create(
ctx, param_type, clang::CK_IntegralCast, zero,
/*BasePath=*/nullptr, clang::VK_PRValue, clang::FPOptionsOverride()
);
} else {
LOG(ERROR) << "Failed to create default value for parameter of type '"
<< param_type.getAsString() << "'\n";
return nullptr;
}
}
/**
* Helper function to create a builtin call expression.
*/
clang::Expr *create_builtin_call(
const clang::ASTContext &ctx, clang::Sema &sema,
const clang::Builtin::ID builtin_id, std::vector< clang::Expr * > &args,
const clang::SourceLocation loc
) {
// Get the builtin name and create a lookup result
const auto name = ctx.BuiltinInfo.getName(builtin_id);
const clang::LookupResult r(
sema, &ctx.Idents.get(name), loc, clang::Sema::LookupOrdinaryName
);
auto *II = r.getLookupName().getAsIdentifierInfo();
// Get the builtin type
clang::ASTContext::GetBuiltinTypeError error{};
const auto ty = ctx.GetBuiltinType(builtin_id, error);
assert(!error && "Failed to get builtin type");
// Create the builtin declaration
auto *builtin_decl = sema.CreateBuiltin(II, ty, builtin_id, loc);
// Create a DeclRefExpr for the builtin. ctx is const here, so we
// can't allocate a virtual buffer; reuse the caller-provided loc
// which is already valid by contract.
auto *decl_ref = clang::DeclRefExpr::Create(
ctx, clang::NestedNameSpecifierLoc(), loc, builtin_decl,
false, loc, builtin_decl->getType(), clang::VK_PRValue
);
// Build the call expression
auto result = sema.BuildCallExpr(nullptr, decl_ref, loc, args, loc);
assert(!result.isInvalid() && "Failed to build builtin call expr");
return result.getAs< clang::Expr >();
}
/**
* @brief Look up or create an opaque external function placeholder in the TU.
*
* Used by create_userdefined to emit a best-effort call expression that
* preserves operation inputs for downstream analysis.
*
* @param fn_name Name of the placeholder function.
* @param ret_type Return type of the placeholder.
* @param param_types Parameter types; must be non-empty (variadic with zero
* fixed params violates "prototyped function must have at
* least one non-variadic input").
* @param op_loc Source location for the declaration.
*/
clang::FunctionDecl *lookup_or_create_opaque_fn( // NOLINT
clang::ASTContext &ctx, const std::string &fn_name, clang::QualType ret_type,
llvm::ArrayRef< clang::QualType > param_types, clang::SourceLocation op_loc
) {
auto &ident = ctx.Idents.get(fn_name);
auto lookup_result =
ctx.getTranslationUnitDecl()->lookup(clang::DeclarationName(&ident));
for (auto *d : lookup_result) {
if (auto *fd = llvm::dyn_cast< clang::FunctionDecl >(d)) {
return fd;
}
}
// Ensure at least one non-variadic param (LLVM/CIR requirement)
llvm::SmallVector< clang::QualType, 4 > params(param_types.begin(), param_types.end());
if (params.empty()) {
params.push_back(ctx.VoidPtrTy);
}
clang::FunctionProtoType::ExtProtoInfo epi;
epi.Variadic = false;
auto fn_type = ctx.getFunctionType(ret_type, params, epi);
auto *fn_decl = clang::FunctionDecl::Create(
ctx, ctx.getTranslationUnitDecl(), op_loc, op_loc,
clang::DeclarationName(&ident), fn_type,
ctx.getTrivialTypeSourceInfo(fn_type), clang::SC_Extern
);
fn_decl->setDeclContext(ctx.getTranslationUnitDecl());
ctx.getTranslationUnitDecl()->addDecl(fn_decl);
return fn_decl;
}
// Bind a Stmt* to an Expr*, logging and returning nullptr on
// null/non-Expr. Avoids `clang::dyn_cast<>(nullptr)`, which asserts.
// Use the `AS_EXPR_OR_NULL` macro at call sites — it captures
// `__FUNCTION__` at the caller, which a default argument cannot.
inline clang::Expr *as_expr_or_null(
clang::Stmt *stmt, const char *op_label, const std::string &key
) {
if (!stmt) {
LOG(ERROR) << op_label << ": varnode produced null Stmt. key: " << key;
return nullptr;
}
auto *expr = clang::dyn_cast< clang::Expr >(stmt);
if (!expr) {
LOG(ERROR) << op_label << ": varnode is not an Expr. key: " << key;
return nullptr;
}
return expr;
}
} // namespace
// Caller-context wrapper: `__FUNCTION__` expands at the call site so the
// log line names the enclosing OpBuilder::create_*, which is impossible
// to achieve with a default argument (it would name as_expr_or_null itself).
#define AS_EXPR_OR_NULL(stmt, key) as_expr_or_null((stmt), __FUNCTION__, (key))
/**
* Performs an implicit and explicit cast of an expression to a specified type,
* falling back to a manual pointer-based cast if necessary.
*/
clang::Expr *OpBuilder::make_cast(
clang::ASTContext &ctx, clang::Expr *expr, const clang::QualType &to_type,
clang::SourceLocation loc
) {
if (expr == nullptr || to_type.isNull()) {
LOG(ERROR) << "Invalid expr of type to perform explicit cast";
return {};
}
auto from_type = expr->getType();
if (ctx.hasSameUnqualifiedType(from_type, to_type)) {
return expr;
}
// Widen a sub-pointer-width integer to uintptr first so the final
// int->pointer cast is width-exact (avoids -Wint-to-pointer-cast).
if (to_type->isPointerType() && from_type->isIntegerType()) {
auto uintptr_ty = ctx.getUIntPtrType();
if (ctx.getTypeSize(from_type) < ctx.getTypeSize(uintptr_ty)) {
expr = make_cast(ctx, expr, uintptr_ty, loc);
if (!expr) {
return nullptr;
}
from_type = expr->getType();
}
}
// CIRGen's emitCallee rejects implicit BitCast on a callee;
// emit an explicit CStyleCastExpr instead.
if (to_type->isPointerType()
&& to_type->getPointeeType()->isFunctionType())
{
auto *cast_expr = make_explicit_cast(ctx, expr, to_type, loc);
if (cast_expr) return cast_expr;
}
// When casting from an array type (e.g. string literal const char[N]) to a
// pointer type, apply array-to-pointer decay first.
if (from_type->isArrayType() && to_type->isPointerType()) {
auto decayed = ctx.getDecayedType(from_type);
expr = make_implicit_cast(
ctx, expr, decayed, clang::CastKind::CK_ArrayToPointerDecay
);
if (expr) {
from_type = expr->getType();
if (ctx.hasSameUnqualifiedType(from_type, to_type)) {
return expr;
}
}
}
// Note: The exported high-pcode from ghidra may have types that can't be casted causing
// diagnostics errors. For example:
// unsigned int -> struct
// void* -> struct
// struct -> unsigned int
// struct -> void*
// Identify such cases early and make expression doing reinterpret cast.
if (ShouldReinterpretCast(from_type, to_type)) {
auto *cast_expr = make_reinterpret_cast(ctx, expr, to_type, loc);
assert(cast_expr != nullptr && "Failed to create cast expression");
return cast_expr;
}
if (expr->isPRValue()) {
auto *cast_expr =
make_implicit_cast(ctx, expr, to_type, GetCastKind(ctx, from_type, to_type));
if (cast_expr != nullptr) {
return cast_expr;
}
} else {
auto *cast_expr = make_explicit_cast(ctx, expr, to_type, loc);
if (cast_expr != nullptr) {
return cast_expr;
}
}
// For pointer-to-pointer casts (e.g. const char * → unsigned char *),
// prefer a C-style cast over the reinterpret_cast pattern which produces
// the ugly *(T**)&expr form.
if (from_type->isPointerType() && to_type->isPointerType()) {
return make_explicit_cast(ctx, expr, to_type, loc);
}
// Fallback to reinterpret cast like expression
return make_reinterpret_cast(ctx, expr, to_type, loc);
}
clang::Expr *OpBuilder::make_explicit_cast(
clang::ASTContext &ctx, clang::Expr *expr, clang::QualType to_type,
clang::SourceLocation loc
) {
auto cast =
sema().BuildCStyleCastExpr(loc, ctx.getTrivialTypeSourceInfo(to_type), loc, expr);
if (cast.isInvalid()) {
LOG(ERROR) << "make_explicit_cast failed\n";
return nullptr;
}
return cast.getAs< clang::Expr >();
}
clang::Expr *OpBuilder::make_implicit_cast(
clang::ASTContext &ctx, clang::Expr *expr, clang::QualType to_type, clang::CastKind kind
) {
if (expr == nullptr || to_type.isNull()) {
LOG(ERROR) << "Invalid arguments: "
<< (!expr ? "null expression" : "null target type");
return nullptr;
}
if (!expr->isPRValue()) {
switch (kind) {
default:
LOG_FATAL(
"can't implicitly cast glvalue to prvalue with cast kind: {0}",
clang::CastExpr::getCastKindName(kind)
);
case clang::CastKind::CK_Dependent:
case clang::CastKind::CK_LValueToRValue:
case clang::CastKind::CK_ArrayToPointerDecay:
case clang::CastKind::CK_FunctionToPointerDecay:
case clang::CastKind::CK_ToVoid:
case clang::CastKind::CK_NonAtomicToAtomic:
break;
}
}
// Handle CK_LValueToRValue differently because sema function does not do anything
// if SrcTy and DestTy is same.
if (kind == clang::CastKind::CK_LValueToRValue) {
return clang::ImplicitCastExpr::Create(
ctx, expr->getType(), clang::CastKind::CK_LValueToRValue, expr, nullptr,
clang::VK_PRValue, sema().CurFPFeatureOverrides()
);
}
auto result = sema().ImpCastExprToType(expr, to_type, kind);
if (result.isInvalid()) {
LOG(WARNING) << "make_implicit_cast failed, returning original expr\n";
return expr;
}
return result.getAs< clang::Expr >();
}
clang::Expr *OpBuilder::make_reinterpret_cast(
clang::ASTContext &ctx, clang::Expr *expr, clang::QualType to_type,
clang::SourceLocation loc
) {
if (expr == nullptr || to_type.isNull()) {
LOG(ERROR) << "Invalid expr of type to perform reinterpret cast\n";
return nullptr;
}
auto create_temporary_expr = [&](clang::ASTContext &ctx,
clang::Expr *expr) -> clang::Expr * {
if (expr->isPRValue()) {
return sema().CreateMaterializeTemporaryExpr(expr->getType(), expr, true);
}
return expr;
(void) ctx;
};
// A function designator (e.g. a VARNODE_FUNCTION operand used as a
// value) has function type and cannot be materialized or addressed as
// an object — doing so builds a function-typed lvalue temporary that
// classifies as CL_Function and aborts CheckAddressOfOperand. Apply the
// C function-to-pointer decay so we reinterpret the function *pointer*.
if (expr->getType()->isFunctionType()) {
expr = clang::ImplicitCastExpr::Create(
ctx, ctx.getPointerType(expr->getType()),
clang::CK_FunctionToPointerDecay, expr, /*BasePath=*/nullptr,
clang::VK_PRValue, clang::FPOptionsOverride()
);
}
auto *temp_expr = create_temporary_expr(ctx, expr);
auto addrof_expr = sema().CreateBuiltinUnaryOp(loc, clang::UO_AddrOf, temp_expr);
if (addrof_expr.isInvalid()) {
LOG(ERROR) << "make_reinterpret_cast: failed to create AddressOf expression\n";
return nullptr;
}
auto to_pointer_type = ctx.getPointerType(to_type);
auto casted_expr = sema().BuildCStyleCastExpr(
loc, ctx.getTrivialTypeSourceInfo(to_pointer_type), loc,
addrof_expr.getAs< clang::Expr >()
);
if (casted_expr.isInvalid()) {
LOG(ERROR) << "make_reinterpret_cast: failed to create CStyleCast expression\n";
return nullptr;
}
auto deref_expr = sema().CreateBuiltinUnaryOp(
loc, clang::UO_Deref, casted_expr.getAs< clang::Expr >()
);
if (deref_expr.isInvalid()) {
LOG(ERROR) << "make_reinterpret_cast: failed to create Deref expression\n";
return nullptr;
}
return deref_expr.getAs< clang::Expr >();
}
clang::Expr *OpBuilder::cast_pointer_to_int(
clang::ASTContext &ctx, clang::Expr *ptr, clang::QualType target,
clang::SourceLocation loc, PtrToIntExtension kind, std::string_view op_key
) {
assert(ptr != nullptr && ptr->getType()->isPointerType()
&& "cast_pointer_to_int: requires a non-null pointer-typed expression");
switch (kind) {
case PtrToIntExtension::kZero: {
// (target)ptr lowers to ptrtoint+zext — matches INT_ZEXT.
auto *r = make_explicit_cast(ctx, ptr, target, loc);
if (!r) {
LOG(ERROR) << "cast_pointer_to_int (zext): failed to cast to "
<< target.getAsString() << ". key: " << op_key << "\n";
}
return r;
}
case PtrToIntExtension::kSign: {
// (target)(intptr_t)(uintptr_t)ptr — forces sext at the widening
// step. A single (target)ptr would lower as ptrtoint+zext.
auto *r = make_explicit_cast(ctx, ptr, ctx.getUIntPtrType(), loc);
if (r) r = make_explicit_cast(ctx, r, ctx.getIntPtrType(), loc);
if (r) r = make_explicit_cast(ctx, r, target, loc);
if (!r) {
LOG(ERROR) << "cast_pointer_to_int (sext): failed to cast through "
"intptr_t to " << target.getAsString()
<< ". key: " << op_key << "\n";
}
return r;
}
}
LOG_FATAL("cast_pointer_to_int: unhandled PtrToIntExtension value");
}
// INT_ZEXT/INT_SEXT produce integers, but Ghidra sometimes types the result
// as a same-width record (e.g. a one-field `struct CRC32`); casting an
// int/enum to it hard-fails Sema. Substitute a same-width unsigned integer
// when the target is not arithmetic/pointer; the write side reinterprets
// back to the record if needed. (Serializer #250 demotion also fixes this at
// the source; this keeps already-captured JSON working.)
clang::QualType OpBuilder::integer_target_for_int_ext(
clang::ASTContext &ctx, clang::QualType target_type, unsigned op_bytes
) {
if (target_type.isNull()) {
return target_type;
}
if (target_type->isIntegerType() || target_type->isPointerType()
|| target_type->isEnumeralType() || target_type->isBooleanType())
{
return target_type;
}
unsigned bits = op_bytes ? op_bytes * 8u
: static_cast< unsigned >(ctx.getTypeSize(target_type));
auto widened = ctx.getIntTypeForBitwidth(bits, /*Signed=*/false);
return widened.isNull() ? target_type : widened;
}
clang::Expr *OpBuilder::narrow_aggregate_to_integer(
clang::ASTContext &ctx, clang::Expr *expr, clang::SourceLocation loc,
unsigned target_bytes
) {
if (!expr) {
return nullptr;
}
auto from_type = expr->getType();
if (!from_type->isRecordType() && !from_type->isArrayType()) {
return nullptr;
}
auto storage_bits = static_cast< unsigned >(ctx.getTypeSize(from_type));
// Prefer `expr[0]` over a whole-aggregate reinterpret when the
// target width is exactly one element. Require the array to have
// at least one element so the literal `0` index is in-bounds.
if (target_bytes != 0 && from_type->isArrayType()) {
if (const auto *array_type = ctx.getAsArrayType(from_type)) {
auto elem_type = array_type->getElementType();
auto elem_bits = static_cast< unsigned >(ctx.getTypeSize(elem_type));
if (elem_type->isIntegerType() && elem_bits == target_bytes * 8u
&& elem_bits > 0 && storage_bits >= elem_bits)
{
auto *zero = clang::IntegerLiteral::Create(
ctx,
llvm::APInt(ctx.getIntWidth(ctx.IntTy), 0),
ctx.IntTy, loc);
auto subscript = sema().CreateBuiltinArraySubscriptExpr(
expr, loc, zero, loc);
if (!subscript.isInvalid()) {
return subscript.getAs< clang::Expr >();
}
}
}
}
// Reinterpret-cast fallback at `target_bytes` (or the aggregate's
// full size when target_bytes == 0). Refuse when the requested
// width exceeds the storage — `*(uintN_t*)&arr` would over-read
// past the aggregate. Caller should loud-refuse instead.
auto size_bits = (target_bytes != 0)
? target_bytes * 8u
: storage_bits;
if (storage_bits > 0 && size_bits > storage_bits) {
return nullptr;
}
clang::QualType int_type;
switch (size_bits) {
case 8: int_type = ctx.UnsignedCharTy; break;
case 16: int_type = ctx.UnsignedShortTy; break;
case 32: int_type = ctx.UnsignedIntTy; break;
case 64: int_type = ctx.UnsignedLongLongTy; break;
case 128:
if (!ctx.UnsignedInt128Ty.isNull()) {
int_type = ctx.UnsignedInt128Ty;
break;
}
[[fallthrough]];
default:
return nullptr;
}
return make_reinterpret_cast(ctx, expr, int_type, loc);
}
// Coerce a record (struct/union) typed expression to an unsigned integer of
// the same byte size so that it can participate in C arithmetic / bitwise
// operations. Returns the expression unchanged if it is not a record type.
clang::Expr *OpBuilder::coerce_record_to_integer(
clang::ASTContext &ctx, clang::Expr *expr, clang::SourceLocation loc,
bool quiet_oversized
) {
if (!expr || !expr->getType()->isRecordType()) {
return expr;
}
auto size_bits = ctx.getTypeSize(expr->getType());
clang::QualType int_type;
if (size_bits <= 8) {
int_type = ctx.UnsignedCharTy;
} else if (size_bits <= 16) {
int_type = ctx.UnsignedShortTy;
} else if (size_bits <= 32) {
int_type = ctx.UnsignedIntTy;
} else if (size_bits <= 64) {
int_type = ctx.UnsignedLongLongTy;
} else if (size_bits <= 128 && !ctx.UnsignedInt128Ty.isNull()) {
int_type = ctx.UnsignedInt128Ty;
} else {
// Too wide for any integer type — return unchanged. Callers that
// don't need a scalar (e.g. ADDRESS_OF) pass quiet_oversized to mute
// the otherwise-misleading warning.
if (!quiet_oversized) {
LOG(WARNING) << "coerce_record_to_integer: record is " << size_bits
<< " bits, too large for integer coercion\n";
}
return expr;
}
return make_reinterpret_cast(ctx, expr, int_type, loc);
}
std::pair< clang::Stmt *, bool > OpBuilder::materialize_call_return(
clang::ASTContext &ctx, clang::Expr *call_expr,
clang::QualType ret_type, const Operation &op,
clang::SourceLocation loc
) {
auto var_name = "__call_ret_"
+ std::to_string(function_builder().call_ret_counter++);
auto *var_decl = create_variable_decl(
ctx, sema().CurContext, var_name, ret_type, loc);
var_decl->setIsUsed();
sema().CurContext->addDecl(var_decl);
// Bare DeclStmt pushed to pending (will be hoisted with other decls)
auto *decl_stmt = create_decl_stmt(ctx, var_decl, loc);
function_builder().pending_materialized.push_back(decl_stmt);
// Assignment: __call_ret_N = call_expr (stays in-place)
auto *ref = clang::DeclRefExpr::Create(
ctx, clang::NestedNameSpecifierLoc(), clang::SourceLocation(),
var_decl, false, loc, ret_type, clang::VK_LValue);
auto *assign = create_assign_operation(ctx, call_expr, ref, loc);
if (op.has_return_value.value_or(false)) {
// Downstream op will consume via create_temporary.
// Cache a DeclRefExpr so the consumer gets the temp var.
auto *ref2 = clang::DeclRefExpr::Create(
ctx, clang::NestedNameSpecifierLoc(), clang::SourceLocation(),
var_decl, false, loc, ret_type, clang::VK_LValue);
function_builder().operation_stmts.emplace(op.key, ref2);
return std::make_pair(assign, false);
}
// No downstream consumer — emit assignment + (void)cast.
auto *ref2 = clang::DeclRefExpr::Create(
ctx, clang::NestedNameSpecifierLoc(), clang::SourceLocation(),
var_decl, false, loc, ret_type, clang::VK_LValue);
auto *void_cast = clang::CStyleCastExpr::Create(
ctx, ctx.VoidTy, clang::VK_PRValue, clang::CK_ToVoid, ref2,
nullptr, clang::FPOptionsOverride(),
ctx.CreateTypeSourceInfo(ctx.VoidTy), loc, loc);
function_builder().pending_materialized.push_back(assign);
return std::make_pair(clang::dyn_cast< clang::Stmt >(void_cast), false);
}
clang::Stmt *OpBuilder::create_assign_operation(
clang::ASTContext &ctx, clang::Expr *input_expr, clang::Expr *output_expr,
clang::SourceLocation loc
) {
if ((input_expr == nullptr) || (output_expr == nullptr)) {
return {};
}
if (loc.isInvalid()) loc = VirtualLoc(ctx);
clang::QualType input_type = input_expr->getType();
clang::QualType output_type = output_expr->getType();
// A function designator is not an assignable lvalue (e.g. a
// VARNODE_FUNCTION used as a store target). Attempting `func = value`
// makes CreateBuiltinBinOp emit a hard "expression is not assignable"
// diagnostic that poisons codegen; bail loudly instead.
if (output_type->isFunctionType()) {
LOG(ERROR) << "create_assign_operation: assignment target has function "
"type '" << output_type.getAsString()
<< "'; dropping non-assignable store\n";
return nullptr;
}
// Scalar → array: lower as a pointer-cast partial store
// `*(input_type *)&output[0] = input`. Width-agnostic — the
// overflow case (input wider than buffer) is preserved
// faithfully for downstream transform passes.
const bool output_is_array = output_type->isArrayType();
const bool input_is_array = input_type->isArrayType();
if (output_is_array && !input_is_array
&& !ctx.hasSameUnqualifiedType(input_type, output_type)) {
const auto *array_type = ctx.getAsArrayType(output_type);
if (array_type != nullptr
&& (input_type->isIntegerType() || input_type->isPointerType())
&& ctx.getTypeSize(input_type) > 0)
{
auto elem_type = array_type->getElementType();
auto *zero = clang::IntegerLiteral::Create(
ctx,
llvm::APInt(ctx.getIntWidth(ctx.IntTy), 0),
ctx.IntTy, loc);
auto subscript_res = sema().CreateBuiltinArraySubscriptExpr(
output_expr, loc, zero, loc);
if (!subscript_res.isInvalid()) {
auto *first_elem = subscript_res.getAs< clang::Expr >();
if (first_elem != nullptr) {
// When the scalar exactly fills one element, emit a clean
// element assignment `output[0] = (elem)input` — what
// Ghidra's own HighVariable model recovers. Otherwise the
// scalar is wider/narrower than the element, so fall back
// to a width-faithful pointer-cast partial store
// `*(input_type *)&output[0] = input`, which preserves the
// exact byte width (and any overflow into following
// elements) for downstream transform passes.
clang::Expr *lhs = first_elem;
clang::Expr *rhs = input_expr;
// The clean `output[0] = (elem)input` form is only valid
// when the element is a scalar. For an aggregate element
// (e.g. a 2-D array or array-of-struct), `output[0]` is an
// array/record lvalue that cannot take a scalar assignment,
// so keep the width-faithful reinterpret partial store.
if (ctx.getTypeSize(input_type) == ctx.getTypeSize(elem_type)
&& elem_type->isScalarType()) {
if (!ctx.hasSameUnqualifiedType(input_type, elem_type)) {
rhs = make_cast(ctx, input_expr, elem_type, loc);
}
} else {
lhs = make_reinterpret_cast(ctx, first_elem, input_type, loc);
}
if (lhs != nullptr && rhs != nullptr) {
auto assign_res = sema().CreateBuiltinBinOp(
loc, clang::BO_Assign, lhs, rhs);
if (!assign_res.isInvalid()) {
return assign_res.getAs< clang::Stmt >();
}
}
}
}
}
// Residual: AST construction failed. Real diag so
// diag_errors bumps and main aborts codegen.
auto &diags = sema().getDiagnostics();
unsigned diag_id = diags.getCustomDiagID(
clang::DiagnosticsEngine::Error,
"create_assign_operation: scalar→array lowering failed "
"for '%0' → '%1'");
diags.Report(loc, diag_id)
<< input_type.getAsString()
<< output_type.getAsString();
return nullptr;
}
// Handle exact type match: no cast required
if (ctx.hasSameUnqualifiedType(input_type, output_type)) {
// Array types are not directly assignable in C; use element-wise copy
if (output_type->isArrayType() || output_type->isConstantArrayType()) {
return create_array_assignment_operation(ctx, input_expr, output_expr, loc);
}
auto assign_operation =
sema().CreateBuiltinBinOp(loc, clang::BO_Assign, output_expr, input_expr);
assert(!assign_operation.isInvalid());
return assign_operation.getAs< clang::Stmt >();
}
// When the input is a string literal (array type) being assigned to a
// pointer, apply array-to-pointer decay first.
if (clang::isa< clang::StringLiteral >(input_expr)
&& input_type->isArrayType() && output_type->isPointerType()) {
auto decayed = ctx.getDecayedType(input_type);
auto *decayed_expr = make_implicit_cast(
ctx, input_expr, decayed, clang::CastKind::CK_ArrayToPointerDecay
);
if (decayed_expr) {
input_expr = decayed_expr;
input_type = input_expr->getType();
}
}
auto *cast_expr = make_cast(ctx, input_expr, output_type, loc);
assert(cast_expr != nullptr && "Failed to create cast expressions!");
if (output_type->isArrayType() || output_type->isConstantArrayType()) {
return create_array_assignment_operation(ctx, cast_expr, output_expr, loc);
}
auto assign_operation =
sema().CreateBuiltinBinOp(loc, clang::BO_Assign, output_expr, cast_expr);
assert(!assign_operation.isInvalid());
return assign_operation.getAs< clang::Stmt >();
}
clang::Stmt *OpBuilder::create_array_assignment_operation(
clang::ASTContext &ctx, clang::Expr *input_expr, clang::Expr *output_expr,
clang::SourceLocation loc
) {
if ((input_expr == nullptr) || (output_expr == nullptr)) {
return nullptr;
}
if (loc.isInvalid()) loc = VirtualLoc(ctx);
auto to_type = output_expr->getType();
auto *elem_type = to_type->getPointeeOrArrayElementType();
auto num_elements = ctx.getTypeSize(to_type) / ctx.getTypeSize(elem_type);
clang::SmallVector< clang::Stmt *, 4 > body;
auto *index = clang::VarDecl::Create(
ctx, sema().CurContext, loc, loc, &ctx.Idents.get("i"), ctx.IntTy, nullptr,
clang::SC_None
);
index->setIsUsed();
auto *index_init = clang::IntegerLiteral::Create(
ctx, llvm::APInt(static_cast< unsigned >(ctx.getTypeSize(ctx.IntTy)), 0), ctx.IntTy,
loc
);
index->setInit(index_init);
auto *index_decl = new (ctx) clang::DeclStmt(clang::DeclGroupRef(index), loc, loc);
auto *index_ref = clang::DeclRefExpr::Create(
ctx, clang::NestedNameSpecifierLoc(), clang::SourceLocation(), index, false,
VirtualLoc(ctx), index->getType(), clang::VK_LValue
);
auto *cond_expr = sema()
.BuildBinOp(
sema().getCurScope(), loc, clang::BO_LT, index_ref,
clang::IntegerLiteral::Create(
ctx, llvm::APInt(32, num_elements), ctx.IntTy, loc
)
)
.get();
auto *inc_expr =
sema().BuildUnaryOp(sema().getCurScope(), loc, clang::UO_PreInc, index_ref).get();
// Array assignment: LHS[i] = RHS[i];
auto *lhs_expr =
sema().CreateBuiltinArraySubscriptExpr(output_expr, loc, index_ref, loc).get();
auto *rhs_expr =
sema().CreateBuiltinArraySubscriptExpr(input_expr, loc, index_ref, loc).get();
auto *assign_expr =
sema()
.BuildBinOp(sema().getCurScope(), loc, clang::BO_Assign, lhs_expr, rhs_expr)
.get();
// Wrap assignment in a CompoundStmt (loop body)
body.push_back(assign_expr);
auto *loop_body =
clang::CompoundStmt::Create(ctx, body, sema().CurFPFeatureOverrides(), loc, loc);
// Set the condVar to nullptr to avoid redeclaration. The ForStmt redeclare the
// conditional stmt causing conflit with init stmt.
return new (ctx) clang::ForStmt(
ctx, index_decl, cond_expr, nullptr, inc_expr, loop_body, loc, loc, loc
);
}
std::optional< clang::QualType > OpBuilder::lookup_op_type(const Operation &op) {
if (!op.type.has_value()) {
LOG(ERROR) << "Operation missing type field. key: " << op.key;
return std::nullopt;
}
auto it = type_builder().GetSerializedTypes().find(*op.type);
if (it == type_builder().GetSerializedTypes().end()) {
LOG(ERROR) << "Operation type not found in serialized types. key: " << op.key;
return std::nullopt;
}
return it->second;
}
std::pair< clang::Stmt *, bool > OpBuilder::create_copy(
clang::ASTContext &ctx, const Function &function, const Operation &op
) {
if (op.inputs.empty()) {
LOG(ERROR) << "Copy operation does not have input operand. key: " << op.key << "\n";
return { nullptr, false };
}
auto *input_expr =
AS_EXPR_OR_NULL(create_varnode(ctx, function, op.inputs.front()), op.key);
if (!input_expr) {
return { nullptr, false };
}
if (!op.output) {
// if copy operation has no output, return input expression that will get merged
// to next operation.
return { input_expr, true };
}
auto *output_expr =
AS_EXPR_OR_NULL(create_varnode(ctx, function, *op.output), op.key);
if (!output_expr) {
return { nullptr, false };
}
return { create_assign_operation(
ctx, input_expr, output_expr,
SourceLocation(ctx.getSourceManager(), op.key)
),
false };
}
std::pair< clang::Stmt *, bool > OpBuilder::create_load(
clang::ASTContext &ctx, const Function &function, const Operation &op
) {
if (op.inputs.empty()) {
LOG(ERROR) << "Load operation with no input operand. key: " << op.key << "\n";
return { nullptr, false };
}
auto merge_to_next = !op.output.has_value();
auto *input_expr =
AS_EXPR_OR_NULL(create_varnode(ctx, function, op.inputs[0]), op.key);
if (!input_expr) {
return { nullptr, false };
}
auto op_loc = SourceLocation(ctx.getSourceManager(), op.key);
// When the input is a string literal, the LOAD is semantically a no-op:
// the string literal already IS the value. Just let it decay from its
// array type (const char[N]) to a pointer (const char *) via the standard
// array-to-pointer implicit cast, avoiding the *(T**)&"..." pattern that
// make_reinterpret_cast would otherwise produce.
if (clang::isa< clang::StringLiteral >(input_expr)) {
clang::Expr *result_expr = make_implicit_cast(
ctx, input_expr, ctx.getDecayedType(input_expr->getType()),
clang::CastKind::CK_ArrayToPointerDecay
);
if (!result_expr) {
result_expr = input_expr;
}
if (merge_to_next) {
return { result_expr, true };
}
auto *output_expr =
AS_EXPR_OR_NULL(create_varnode(ctx, function, *op.output), op.key);
if (!output_expr) {
return { nullptr, false };
}
return { create_assign_operation(ctx, result_expr, output_expr, op_loc), false };
}
if (op.type) {
auto op_type_opt = lookup_op_type(op);
if (!op_type_opt) {
return {};
}
auto pointer_type = ctx.getPointerType(*op_type_opt);
auto *cast_expr = make_cast(ctx, input_expr, pointer_type, op_loc);
if (!cast_expr) {
LOG(ERROR) << "Failed to make cast expression for LOAD. key: " << op.key;
return {};
}
input_expr = cast_expr;
}
// Dereferencing a void* is ill-formed in C. When no explicit op.type cast has been
// applied above and the pointer is still void*, cast it to the output varnode's type
// (if known) or uint8_t* as a last resort.
if (input_expr->getType()->isVoidPointerType()) {
clang::QualType pointee = op.output.has_value()
? get_varnode_type(ctx, *op.output)
: ctx.UnsignedCharTy;
input_expr = make_cast(ctx, input_expr, ctx.getPointerType(pointee), op_loc);
assert(input_expr != nullptr && "Failed to cast void* for load");
}
// Cancel *(&expr) from PTRADD's &base[index] to produce base[index].
clang::Expr *result_expr = simplify_deref_addrof(input_expr);
if (!result_expr) {
auto derefed_expr = sema().CreateBuiltinUnaryOp(
SourceLocation(ctx.getSourceManager(), op.key), clang::UO_Deref,
clang::dyn_cast< clang::Expr >(input_expr)
);
result_expr = derefed_expr.getAs< clang::Expr >();
}
if (merge_to_next) {
return std::make_pair(result_expr, merge_to_next);
}
auto *output_expr =
AS_EXPR_OR_NULL(create_varnode(ctx, function, *op.output), op.key);
if (!output_expr) {
return { nullptr, false };
}
return { create_assign_operation(
ctx, result_expr, output_expr,
SourceLocation(ctx.getSourceManager(), op.key)
),
false };
}
// Ghidra can give a STORE a bare integer address or a void*, which fail
// Sema's indirection check. Cast those to a pointer of the value's type so
// the store lowers to *(T *)addr = value; a real non-void pointer passes
// through unchanged. Returns nullptr if the cast cannot be built.
clang::Expr *OpBuilder::coerce_store_address(
clang::ASTContext &ctx, clang::Expr *addr, clang::Expr *value,
const Operation &op, clang::SourceLocation op_loc
) {