-
-
Notifications
You must be signed in to change notification settings - Fork 3.2k
Expand file tree
/
Copy pathanal_tp.c
More file actions
1945 lines (1841 loc) · 56.8 KB
/
anal_tp.c
File metadata and controls
1945 lines (1841 loc) · 56.8 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
/* radare - LGPL - Copyright 2016-2025 - oddcoder, sivaramaaa, pancake */
/* type matching - type propagation */
#include <r_anal.h>
#define LOOP_MAX 10
#define TYPE_MATCH_MAX_BACKTRACE 512
typedef struct type_trace_change_reg_t {
int idx;
ut32 cc;
char *name;
ut64 data;
ut64 odata;
} TypeTraceRegChange;
static void type_trace_reg_change_fini(void *data) {
if (data) {
TypeTraceRegChange *change = data;
free (change->name);
}
}
typedef struct type_trace_mem_range_t {
int idx;
ut32 cc;
ut64 addr;
ut32 len;
ut8 *data;
ut8 *odata;
} TypeTraceMemRange;
static void type_trace_mem_range_fini(void *data) {
TypeTraceMemRange *range = data;
if (range) {
free (range->data);
free (range->odata);
}
}
typedef struct {
char *name;
ut64 value;
// TODO: size
} TypeTraceRegAccess;
typedef struct {
char *data;
ut64 addr;
// TODO: size
} TypeTraceMemoryAccess;
typedef struct {
union {
TypeTraceRegAccess reg;
TypeTraceMemoryAccess mem;
};
bool is_write;
bool is_reg;
} TypeTraceAccess;
typedef struct {
ut64 addr;
ut32 start;
ut32 end; // 1 past the end of the op for this index
} TypeTraceOp;
static inline void tt_fini_access(TypeTraceAccess *access) {
if (access->is_reg) {
free (access->reg.name);
return;
}
free (access->mem.data);
}
R_VEC_TYPE(VecTraceOp, TypeTraceOp);
R_VEC_TYPE_WITH_FINI(VecAccess, TypeTraceAccess, tt_fini_access);
R_VEC_TYPE_WITH_FINI(VecRegChange, TypeTraceRegChange, type_trace_reg_change_fini);
R_VEC_TYPE_WITH_FINI(VecMemRange, TypeTraceMemRange, type_trace_mem_range_fini);
typedef struct {
VecTraceOp ops;
VecAccess accesses;
HtUU *loop_counts;
} TypeTraceDB;
typedef struct type_trace_t {
TypeTraceDB db;
int idx;
ut32 cc;
int end_idx;
int cur_idx;
RReg *reg;
HtUP *registers;
VecMemRange memory;
ut32 voy[4];
RStrBuf rollback; // ESIL string to rollback state (inspired by PR #24428)
bool enable_rollback;
// TODO: Add REsil instance here
} TypeTrace;
#define CMP_REG_CHANGE(x, y) ((x) - ((TypeTraceRegChange *)y)->idx)
static void update_trace_db_op(TypeTraceDB *db) {
const ut32 trace_op_len = VecTraceOp_length (&db->ops);
if (!trace_op_len) {
return;
}
TypeTraceOp *last = VecTraceOp_at (&db->ops, trace_op_len - 1);
if (!last) {
return;
}
const ut32 vec_idx = VecAccess_length (&db->accesses);
if (!vec_idx) {
R_LOG_ERROR ("Invalid access database");
return;
}
last->end = vec_idx; // - 1;
}
static void type_trace_voyeur_reg_read(void *user, const char *name, ut64 val) {
R_RETURN_IF_FAIL (user && name);
char *name_dup = strdup (name);
if (!name_dup) {
R_LOG_ERROR ("Failed to allocate(strdup) memory for storing access");
return;
}
TypeTraceDB *db = user;
TypeTraceAccess *access = VecAccess_emplace_back (&db->accesses);
if (!access) {
free (name_dup);
R_LOG_ERROR ("Failed to allocate memory for storing access");
return;
}
access->reg.name = name_dup;
access->reg.value = val;
access->is_reg = true;
access->is_write = false;
update_trace_db_op (db);
}
static void add_reg_change(TypeTrace *trace, RRegItem *ri, ut64 data, ut64 odata) {
R_RETURN_IF_FAIL (trace && ri);
ut64 addr = ri->offset | (ri->arena << 16);
VecRegChange *vreg = ht_up_find (trace->registers, addr, NULL);
if (R_UNLIKELY (!vreg)) {
vreg = R_NEW0 (VecRegChange);
if (R_UNLIKELY (!vreg)) {
R_LOG_ERROR ("creating a register vector");
return;
}
VecRegChange_init (vreg);
ht_up_insert (trace->registers, addr, vreg);
}
TypeTraceRegChange *reg = VecRegChange_emplace_back (vreg);
if (reg) {
*reg = (TypeTraceRegChange){ trace->cur_idx, trace->cc++, strdup (ri->name), data, odata };
}
}
static void type_trace_voyeur_reg_write(void *user, const char *name, ut64 old, ut64 val) {
R_RETURN_IF_FAIL (user && name);
TypeTrace *trace = user;
RRegItem *ri = r_reg_get (trace->reg, name, -1);
if (!ri) {
return;
}
char *name_dup = strdup (name);
if (!name_dup) {
r_unref (ri);
R_LOG_ERROR ("Failed to allocate(strdup) memory for storing access");
return;
}
TypeTraceAccess *access = VecAccess_emplace_back (&trace->db.accesses);
if (!access) {
free (name_dup);
r_unref (ri);
R_LOG_ERROR ("Failed to allocate memory for storing access");
return;
}
access->is_reg = true;
access->reg.name = name_dup;
access->reg.value = val;
access->is_write = true;
if (trace->enable_rollback) {
r_strbuf_prependf (&trace->rollback, "0x%" PFMT64x ",%s,:=,", old, name);
}
add_reg_change (trace, ri, val, old);
update_trace_db_op (&trace->db);
r_unref (ri);
}
static void type_trace_voyeur_mem_read(void *user, ut64 addr, const ut8 *buf, int len) {
R_RETURN_IF_FAIL (user && buf && (len > 0));
char *hexbuf = r_hex_bin2strdup (buf, len); // why?
if (!hexbuf) {
R_LOG_ERROR ("r_hex_bin2strdup fail");
return;
}
TypeTraceDB *db = user;
TypeTraceAccess *access = VecAccess_emplace_back (&db->accesses);
if (!access) {
free (hexbuf);
R_LOG_ERROR ("Failed to allocate memory for storing access");
return;
}
access->is_reg = false;
access->mem.data = hexbuf;
access->mem.addr = addr;
access->is_write = false;
update_trace_db_op (db);
}
static void type_trace_voyeur_mem_write(void *user, ut64 addr, const ut8 *old, const ut8 *buf, int len) {
R_RETURN_IF_FAIL (user && buf && (len > 0));
char *hexbuf = r_hex_bin2strdup (buf, len); // why?
if (!hexbuf) {
R_LOG_ERROR ("r_hex_bin2strdup fail");
return;
}
TypeTrace *trace = user;
TypeTraceAccess *access = VecAccess_emplace_back (&trace->db.accesses);
if (!access) {
free (hexbuf);
R_LOG_ERROR ("Failed to allocate memory for storing access");
return;
}
access->is_reg = false;
access->mem.data = hexbuf;
access->mem.addr = addr;
access->is_write = true;
if (trace->enable_rollback && old) {
int i;
for (i = len - 1; i >= 0; i--) {
r_strbuf_prependf (&trace->rollback,
"0x%02x,0x%" PFMT64x ",=[1],", old[i], addr + i);
}
}
TypeTraceMemRange *mem = VecMemRange_emplace_back (&trace->memory);
if (!mem) {
R_LOG_ERROR ("Failed to allocate memory for storing access");
goto update_db;
}
*mem = (TypeTraceMemRange){ 0 };
ut8 *data = malloc (len);
if (!data) {
VecMemRange_erase_back (&trace->memory, mem);
R_LOG_ERROR ("Failed to allocate memory for storing access");
goto update_db;
}
memcpy (data, buf, len);
ut8 *odata = NULL;
if (old) {
odata = malloc (len);
if (!odata) {
free (data);
mem->data = NULL;
mem->odata = NULL;
VecMemRange_erase_back (&trace->memory, mem);
R_LOG_ERROR ("Failed to allocate memory for storing access");
goto update_db;
}
memcpy (odata, old, len);
}
*mem = (TypeTraceMemRange){ trace->idx, trace->cc++, addr, (ut32)len, data, odata };
update_db:
update_trace_db_op (&trace->db);
}
static void htup_regvec_free(HtUPKv *kv) {
if (kv && kv->value) {
VecRegChange_free (kv->value);
}
}
static void trace_db_init(TypeTraceDB *db) {
VecTraceOp_init (&db->ops);
VecAccess_init (&db->accesses);
db->loop_counts = ht_uu_new0 ();
}
static void trace_db_fini(TypeTraceDB *db) {
if (db) {
VecTraceOp_fini (&db->ops);
VecAccess_fini (&db->accesses);
ht_uu_free (db->loop_counts);
db->loop_counts = NULL;
}
}
static bool type_trace_init(TypeTrace *trace, REsil *esil, RReg *reg) {
R_RETURN_VAL_IF_FAIL (trace && esil && reg, false);
*trace = (const TypeTrace){ 0 };
trace_db_init (&trace->db);
r_strbuf_init (&trace->rollback);
trace->enable_rollback = false; // Disabled by default for performance
VecMemRange_init (&trace->memory);
trace->registers = ht_up_new (NULL, htup_regvec_free, NULL);
if (!trace->registers) {
goto fail_registers_ht;
}
trace->voy[R_ESIL_VOYEUR_REG_READ] = r_esil_add_voyeur (esil, &trace->db,
type_trace_voyeur_reg_read, R_ESIL_VOYEUR_REG_READ);
if (R_UNLIKELY (trace->voy[R_ESIL_VOYEUR_REG_READ] == R_ESIL_VOYEUR_ERR)) {
goto fail_regr_voy;
}
trace->voy[R_ESIL_VOYEUR_REG_WRITE] = r_esil_add_voyeur (esil, trace,
type_trace_voyeur_reg_write, R_ESIL_VOYEUR_REG_WRITE);
if (R_UNLIKELY (trace->voy[R_ESIL_VOYEUR_REG_WRITE] == R_ESIL_VOYEUR_ERR)) {
goto fail_regw_voy;
}
trace->voy[R_ESIL_VOYEUR_MEM_READ] = r_esil_add_voyeur (esil, &trace->db,
type_trace_voyeur_mem_read, R_ESIL_VOYEUR_MEM_READ);
if (R_UNLIKELY (trace->voy[R_ESIL_VOYEUR_MEM_READ] == R_ESIL_VOYEUR_ERR)) {
goto fail_memr_voy;
}
trace->voy[R_ESIL_VOYEUR_MEM_WRITE] = r_esil_add_voyeur (esil, trace,
type_trace_voyeur_mem_write, R_ESIL_VOYEUR_MEM_WRITE);
if (R_UNLIKELY (trace->voy[R_ESIL_VOYEUR_MEM_WRITE] == R_ESIL_VOYEUR_ERR)) {
goto fail_memw_voy;
}
trace->reg = reg;
return true;
fail_memw_voy:
r_esil_del_voyeur (esil, trace->voy[R_ESIL_VOYEUR_MEM_READ]);
fail_memr_voy:
r_esil_del_voyeur (esil, trace->voy[R_ESIL_VOYEUR_REG_WRITE]);
fail_regw_voy:
r_esil_del_voyeur (esil, trace->voy[R_ESIL_VOYEUR_REG_READ]);
fail_regr_voy:
ht_up_free (trace->registers);
trace->registers = NULL;
fail_registers_ht:
VecMemRange_fini (&trace->memory);
trace_db_fini (&trace->db);
return false;
}
static ut64 type_trace_loopcount(TypeTrace *trace, ut64 addr) {
bool found = false;
const ut64 count = ht_uu_find (trace->db.loop_counts, addr, &found);
return found? count: 0;
}
static void type_trace_loopcount_increment(TypeTrace *trace, ut64 addr) {
const ut64 count = type_trace_loopcount (trace, addr);
ht_uu_update (trace->db.loop_counts, addr, count + 1);
}
// Execute rollback ESIL to restore state, then clear buffer
static void type_trace_rollback(TypeTrace *trace, REsil *esil) {
R_RETURN_IF_FAIL (trace && esil);
if (r_strbuf_length (&trace->rollback) > 0) {
const char *expr = r_strbuf_get (&trace->rollback);
if (expr && *expr) {
// Disable rollback recording during rollback execution
// to prevent voyeur callbacks from adding to the buffer
bool was_enabled = trace->enable_rollback;
trace->enable_rollback = false;
r_esil_parse (esil, expr);
r_esil_stack_free (esil);
trace->enable_rollback = was_enabled;
}
r_strbuf_fini (&trace->rollback);
r_strbuf_init (&trace->rollback);
}
}
// Clear rollback buffer without executing
static void type_trace_rollback_clear(TypeTrace *trace) {
R_RETURN_IF_FAIL (trace);
r_strbuf_fini (&trace->rollback);
r_strbuf_init (&trace->rollback);
}
static void type_trace_fini(TypeTrace *trace, REsil *esil) {
R_RETURN_IF_FAIL (trace && esil);
trace_db_fini (&trace->db);
r_strbuf_fini (&trace->rollback);
ht_up_free (trace->registers);
trace->registers = NULL;
VecMemRange_fini (&trace->memory);
r_esil_del_voyeur (esil, trace->voy[R_ESIL_VOYEUR_MEM_WRITE]);
r_esil_del_voyeur (esil, trace->voy[R_ESIL_VOYEUR_MEM_READ]);
r_esil_del_voyeur (esil, trace->voy[R_ESIL_VOYEUR_REG_WRITE]);
r_esil_del_voyeur (esil, trace->voy[R_ESIL_VOYEUR_REG_READ]);
r_reg_free (trace->reg);
trace->reg = NULL;
*trace = (const TypeTrace){ 0 };
}
static bool type_trace_op(TypeTrace *trace, REsil *esil, RAnalOp *op) {
R_RETURN_VAL_IF_FAIL (trace && esil && op, false);
const char *expr = r_strbuf_get (&op->esil);
if (R_STR_ISEMPTY (expr)) {
// empty expressions are nops or unimplemented, we can move forward here
return true;
}
trace->cc = 0;
TypeTraceOp *to = VecTraceOp_emplace_back (&trace->db.ops);
if (R_UNLIKELY (!to)) {
R_LOG_ERROR ("Failed to allocate trace op at 0x%08" PFMT64x, op->addr);
return false;
}
ut32 vec_idx = VecAccess_length (&trace->db.accesses);
to->start = vec_idx;
to->end = vec_idx;
to->addr = op->addr;
const bool ret = r_esil_parse (esil, expr);
r_esil_stack_free (esil);
trace->idx++;
trace->end_idx++;
return ret;
}
// TODO: type_trace_restore() for state rollback during backtracking
// was removed as dead code - can be re-implemented if needed for
// more accurate cross-basic-block type propagation
R_VEC_TYPE(RVecUT64, ut64);
R_VEC_TYPE(RVecBuf, ut8);
// TPState - Isolated ESIL environment for type propagation
// Design inspired by RCoreEsil from PR #24428:
// - Centralized ESIL state (esil, reg_if, mem_if)
// - Tracing with rollback capability (tt)
// - Hook callbacks for extensibility
typedef struct tp_state_t {
// ESIL engine and interfaces
REsil esil;
REsilRegInterface reg_if;
REsilMemInterface mem_if;
TypeTrace tt;
ut64 stack_base;
int stack_fd;
ut32 stack_map;
RAnal *anal;
// RConfigHold *hc;
char *cfg_spec;
bool cfg_breakoninvalid;
bool cfg_chk_constraint;
bool cfg_rollback;
bool old_follow;
void (*on_call)(struct tp_state_t *tps, ut64 addr, const char *name);
void *hook_user;
} TPState;
/// BEGIN /////////////////// esil trace helpers ///////////////////////
static int etrace_index(TypeTrace *etrace) {
int len = VecTraceOp_length (&etrace->db.ops);
etrace->cur_idx = len; // > 0? len -1: 0;
return etrace->cur_idx; // VecTraceOp_length (&etrace->db.ops);
}
static ut64 etrace_addrof(TypeTrace *etrace, ut32 idx) {
TypeTraceOp *op = VecTraceOp_at (&etrace->db.ops, idx);
return op? op->addr: 0;
}
typedef bool (*AccessPredicate)(const TypeTraceAccess *access, void *user);
static const TypeTraceAccess *etrace_find_access(TypeTrace *etrace, ut32 idx, AccessPredicate pred, void *user) {
TypeTraceOp *op = VecTraceOp_at (&etrace->db.ops, idx);
if (!op || op->start == op->end) {
return NULL;
}
const TypeTraceAccess *start = VecAccess_at (&etrace->db.accesses, op->start);
const TypeTraceAccess *end = VecAccess_at (&etrace->db.accesses, op->end - 1);
if (!start || !end || start > end) {
return NULL;
}
while (start <= end) {
if (pred (start, user)) {
return start;
}
start++;
}
return NULL;
}
static bool etrace_is_memwrite(const TypeTraceAccess *access, void *user) {
(void)user;
return !access->is_reg && access->is_write;
}
static bool etrace_is_memread(const TypeTraceAccess *access, void *user) {
(void)user;
return !access->is_reg && !access->is_write;
}
static bool etrace_is_regread(const TypeTraceAccess *access, void *user) {
const char *rname = (const char *)user;
return access->is_reg && !access->is_write && !strcmp (rname, access->reg.name);
}
static ut64 etrace_memwrite_addr(TypeTrace *etrace, ut32 idx) {
R_LOG_DEBUG ("memwrite %d %d", etrace->idx, idx);
const TypeTraceAccess *access = etrace_find_access (etrace, idx, etrace_is_memwrite, NULL);
if (access) {
return access->mem.addr;
}
return 0;
}
static bool etrace_have_memread(TypeTrace *etrace, ut32 idx) {
R_LOG_DEBUG ("memread %d %d", etrace->idx, idx);
return etrace_find_access (etrace, idx, etrace_is_memread, NULL) != NULL;
}
static ut64 etrace_regread_value(TypeTrace *etrace, ut32 idx, const char *rname) {
R_LOG_DEBUG ("regread %d %d", etrace->idx, idx);
const TypeTraceAccess *access = etrace_find_access (etrace, idx, etrace_is_regread, (void *)rname);
if (access) {
return access->reg.value;
}
return 0;
}
static const char *etrace_regwrite(TypeTrace *etrace, ut32 idx) {
R_LOG_DEBUG ("regwrite %d %d", etrace->idx, idx);
TypeTraceOp *op = VecTraceOp_at (&etrace->db.ops, idx);
if (op && op->start != op->end) {
TypeTraceAccess *start = VecAccess_at (&etrace->db.accesses, op->start);
TypeTraceAccess *end = VecAccess_at (&etrace->db.accesses, op->end - 1);
if (!start || !end || start > end) {
return NULL;
}
while (start <= end) {
if (start->is_reg && start->is_write) {
return start->reg.name;
}
start++;
}
}
return NULL;
}
/// END ///////////////////// esil trace helpers ///////////////////////
static bool etrace_regwrite_contains(TypeTrace *etrace, ut32 idx, const char *rname) {
R_LOG_DEBUG ("regwrite contains %d %s", idx, rname);
R_RETURN_VAL_IF_FAIL (etrace && rname, false);
TypeTraceOp *op = VecTraceOp_at (&etrace->db.ops, idx); // AAA + 1);
if (op && op->start != op->end) {
TypeTraceAccess *start = VecAccess_at (&etrace->db.accesses, op->start);
TypeTraceAccess *end = VecAccess_at (&etrace->db.accesses, op->end - 1);
if (!start || !end || start > end) {
return false;
}
while (start <= end) {
if (start->is_reg && start->is_write) {
if (!strcmp (rname, start->reg.name)) {
return true;
}
}
start++;
}
}
return false;
}
static bool type_pos_hit(TPState *tps, bool in_stack, int idx, int size, const char *place) {
R_LOG_DEBUG ("Type pos hit %d %d %d %s", in_stack, idx, size, place);
if (in_stack) {
ut64 sp = r_reg_getv (tps->tt.reg, "SP"); // XXX this is slow too and we can cache
const ut64 write_addr = etrace_memwrite_addr (&tps->tt, idx); // AAA -1
return (write_addr == sp + size);
}
return place && etrace_regwrite_contains (&tps->tt, idx, place);
}
static void var_rename(RAnal *anal, RAnalVar *v, const char *name, ut64 addr) {
if (!name || !v) {
return;
}
if (!*name || !strcmp (name, "...")) {
return;
}
bool is_default = (r_str_startswith (v->name, VARPREFIX) || r_str_startswith (v->name, ARGPREFIX));
if (*name == '*') {
name++;
}
// longer name tends to be meaningful like "src" instead of "s1"
if (!is_default && (strlen (v->name) > strlen (name))) {
return;
}
RAnalFunction *fcn = r_anal_get_fcn_in (anal, addr, 0);
if (fcn) {
r_anal_var_rename (anal, v, name);
}
}
static void var_retype(RAnal *anal, RAnalVar *var, const char *vname, const char *type, int ref, bool pfx) {
R_LOG_DEBUG ("Var retype %s %s", var->name, type);
R_RETURN_IF_FAIL (anal && var && type);
// XXX types should be passed without spaces to trim
type = r_str_trim_head_ro (type);
// default type if none is provided
if (!*type) {
type = "int";
}
bool is_ptr = (vname && *vname == '*');
// removing this return makes 64bit vars become 32bit
if (r_str_startswith (type, "int") || (!is_ptr && !strcmp (type, "void"))) {
// default or void type
R_LOG_DEBUG ("DEFAULT NOT DOING THIS");
return;
}
const char *expand = var->type;
if (!strcmp (var->type, "int32_t")) {
expand = "int";
} else if (!strcmp (var->type, "uint32_t")) {
expand = "unsigned int";
} else if (!strcmp (var->type, "uint64_t")) {
expand = "unsigned long long";
}
const char *tmp = strstr (expand, "int");
bool is_default = tmp;
if (!is_default && !r_str_startswith (var->type, "void")) {
// return since type is already propagated
// except for "void *", since "void *" => "char *" is possible
R_LOG_DEBUG ("not default NOT DOING A SHIT HERE");
return;
}
RStrBuf *sb = r_strbuf_new ("");
if (pfx) {
if (is_default && !r_str_startswith (var->type, "signed")) {
r_strbuf_setf (sb, "%s %s", type, tmp);
} else {
r_strbuf_free (sb);
R_LOG_DEBUG ("THIS IS RETURN NOT DOING A SHIT HERE");
return;
}
} else {
r_strbuf_set (sb, type);
}
if (r_str_startswith (r_strbuf_get (sb), "const ")) {
// Dropping const from type
// TODO: Inferring const type
r_strbuf_setf (sb, "%s", type + 6);
}
if (is_ptr) {
// type *ptr => type *
r_strbuf_append (sb, " *");
}
while (ref > 0) {
if (r_str_endswith (r_strbuf_get (sb), "*")) { // type * => type **
r_strbuf_append (sb, "*");
} else { // type => type *
r_strbuf_append (sb, " *");
}
ref--;
}
while (ref < 0) {
char *s = r_strbuf_get (sb);
if (!s) {
break;
}
r_str_trim (s);
if (r_str_endswith (s, "*")) {
r_strbuf_slice (sb, 0, r_strbuf_length (sb) - 1);
}
ref++;
}
char *tmp1 = r_strbuf_get (sb);
if (r_str_startswith (tmp1, "unsigned long long")) {
r_strbuf_set (sb, "uint64_t");
} else if (r_str_startswith (tmp1, "unsigned")) {
r_strbuf_set (sb, "uint32_t");
} else if (r_str_startswith (tmp1, "int")) {
r_strbuf_set (sb, "int32_t");
}
r_anal_var_set_type (anal, var, r_strbuf_get (sb));
r_strbuf_free (sb);
}
static RAnalOp *tp_anal_op(RAnal *anal, ut64 addr, int mask);
static void get_src_regname(RAnal *anal, ut64 addr, char *regname, int size) {
R_RETURN_IF_FAIL (anal && regname && size > 0);
regname[0] = 0;
RAnalOp *op = tp_anal_op (anal, addr, R_ARCH_OP_MASK_VAL | R_ARCH_OP_MASK_ESIL);
if (!op || r_strbuf_is_empty (&op->esil)) {
r_anal_op_free (op);
return;
}
char *op_esil = r_strbuf_get (&op->esil);
char *tmp = strchr (op_esil, ',');
if (tmp) {
*tmp = '\0';
}
RRegItem *ri = r_reg_get (anal->reg, op_esil, -1);
if (ri) {
const char *s = op_esil;
if ((anal->config->bits == 64) && (ri->size == 32)) {
const char *reg = r_reg_32_to_64 (anal->reg, op_esil);
if (reg) {
s = reg;
}
}
if (s) {
r_str_ncpy (regname, s, size);
}
R_LOG_DEBUG ("===================regitem %s", regname);
r_unref (ri);
} else {
R_LOG_DEBUG ("no regitem %s at 0x%" PFMT64x, op_esil, addr);
}
r_anal_op_free (op);
}
static ut64 get_addr(TypeTrace *et, const char *regname, int idx) {
if (R_STR_ISEMPTY (regname)) {
return 0;
}
/// r_strf_var (query, 64, "%d.reg.read.%s", idx, regname);
// return r_num_math (NULL, sdb_const_get (trace, query, 0));
return etrace_regread_value (et, idx, regname);
}
static RAnalCondType cond_invert(RAnal *anal, RAnalCondType cond) {
switch (cond) {
case R_ANAL_CONDTYPE_LE:
return R_ANAL_CONDTYPE_GT;
case R_ANAL_CONDTYPE_LT:
return R_ANAL_CONDTYPE_GE;
case R_ANAL_CONDTYPE_GE:
return R_ANAL_CONDTYPE_LT;
case R_ANAL_CONDTYPE_GT:
return R_ANAL_CONDTYPE_LE;
case R_ANAL_CONDTYPE_AL:
return R_ANAL_CONDTYPE_NV;
case R_ANAL_CONDTYPE_NV:
return R_ANAL_CONDTYPE_AL;
case R_ANAL_CONDTYPE_EQ:
return R_ANAL_CONDTYPE_NE;
case R_ANAL_CONDTYPE_NE:
return R_ANAL_CONDTYPE_EQ;
default:
R_LOG_WARN ("unhandled condition for swapping %d", cond);
break;
}
return 0; // 0 is COND_ALways...
/* I haven't looked into it but I suspect that this might be confusing:
the opposite of any condition not in the list above is "always"? */
}
typedef const char *String;
R_VEC_TYPE(RVecString, String); // no fini, these are owned by SDB
static RAnalOp *tp_anal_op(RAnal *anal, ut64 addr, int mask);
static bool parse_format(TPState *tps, const char *fmt, RVecString *vec) {
if (R_STR_ISEMPTY (fmt)) {
return false;
}
Sdb *s = tps->anal->sdb_fmts;
char arr[32] = { 0 };
const char *ptr = strchr (fmt, '%');
while (ptr) {
ptr++;
// strip [width] specifier
while (isdigit (*ptr)) {
ptr++;
}
r_str_ncpy (arr, ptr, sizeof (arr) - 1);
char *tmp = arr;
while (isalpha (*tmp)) {
tmp++;
}
*tmp = '\0';
r_strf_var (query, 128, "spec.%s.%s", tps->cfg_spec, arr);
const char *type = sdb_const_get (s, query, 0); // maybe better to return an owned pointer here?
if (type) {
RVecString_push_back (vec, &type);
}
// ptr = strchr (ptr + (tmp-arr), '%');
ptr = strchr (ptr, '%');
}
return true;
}
static void retype_callee_arg(RAnal *anal, const char *callee_name, bool in_stack, const char *place, int size, const char *type) {
R_LOG_DEBUG (">>> CALLE ARG");
RAnalFunction *fcn = r_anal_get_function_byname (anal, callee_name);
if (!fcn) {
return;
}
if (in_stack) {
RAnalVar *var = r_anal_function_get_var (fcn, R_ANAL_VAR_KIND_BPV, size - fcn->bp_off + 8);
if (!var) {
return;
}
var_retype (anal, var, NULL, type, false, false);
} else {
RRegItem *item = r_reg_get (anal->reg, place, -1);
if (!item) {
return;
}
RAnalVar *rvar = r_anal_function_get_var (fcn, R_ANAL_VAR_KIND_REG, item->index);
if (!rvar) {
r_unref (item);
return;
}
char *t = strdup (type);
var_retype (anal, rvar, NULL, type, false, false);
RAnalVar *lvar = r_anal_var_get_dst_var (rvar);
if (lvar) {
var_retype (anal, lvar, NULL, t, false, false);
}
free (t);
r_unref (item);
}
}
static bool etrace_memread_contains_addr(TypeTrace *etrace, ut32 idx, ut64 addr) {
TypeTraceOp *op = VecTraceOp_at (&etrace->db.ops, idx);
if (op && op->start != op->end) {
TypeTraceAccess *start = VecAccess_at (&etrace->db.accesses, op->start);
TypeTraceAccess *end = VecAccess_at (&etrace->db.accesses, op->end - 1);
if (!start || !end || start > end) {
return false;
}
while (start <= end) {
if (!start->is_reg && !start->is_write && start->mem.addr == addr) {
return true;
}
start++;
}
}
return false;
}
static bool etrace_memread_first_addr(TypeTrace *etrace, ut32 idx, ut64 *addr) {
TypeTraceOp *op = VecTraceOp_at (&etrace->db.ops, idx);
if (!op || op->start == op->end) {
return false;
}
TypeTraceAccess *start = VecAccess_at (&etrace->db.accesses, op->start);
TypeTraceAccess *end = VecAccess_at (&etrace->db.accesses, op->end - 1);
if (!start || !end || start > end) {
return false;
}
while (start <= end) {
if (!start->is_reg && !start->is_write) {
if (addr) {
*addr = start->mem.addr;
}
return true;
}
start++;
}
return false;
}
#define DEFAULT_MAX 3
#define REGNAME_SIZE 10
#define MAX_INSTR 5
/**
* type match at a call instruction inside another function
*
* \param fcn_name name of the callee
* \param addr addr of the call instruction
* \param baddr addr of the caller function
* \param cc cc of the callee
* \param prev_idx index in the esil trace
* \param userfnc whether the callee is a user function (affects propagation direction)
* \param caddr addr of the callee
*/
static void type_match(TPState *tps, char *fcn_name, ut64 addr, ut64 baddr, const char *cc,
int prev_idx, bool userfnc, ut64 caddr) {
RAnal *anal = tps->anal;
TypeTrace *tt = &tps->tt;
Sdb *TDB = anal->sdb_types;
const int idx = etrace_index (tt) - 1;
const bool verbose = anal->coreb.cfgGetB? anal->coreb.cfgGetB (anal->coreb.core, "types.verbose"): false;
bool stack_rev = false, in_stack = false, format = false;
R_LOG_DEBUG ("type_match %s %" PFMT64x " %" PFMT64x " %s %d", fcn_name, addr, baddr, cc, prev_idx);
if (!fcn_name || !cc) {
return;
}
int i, j, pos = 0, size = 0, max = r_type_func_args_count (TDB, fcn_name);
int lastarg = ST32_MAX;
const char *place = r_anal_cc_arg (anal, cc, lastarg, -1);
r_cons_break_push (r_cons_singleton (), NULL, NULL);
if (place && !strcmp (place, "stack_rev")) {
stack_rev = true;
}
place = r_anal_cc_arg (anal, cc, 0, -1);
if (place && r_str_startswith (place, "stack")) {
in_stack = true;
}
if (verbose && r_str_startswith (fcn_name, "sym.imp.")) {
R_LOG_WARN ("Missing function definition for '%s'", fcn_name + 8);
}
if (!max) {
max = in_stack? DEFAULT_MAX: r_anal_cc_max_arg (anal, cc);
}
// TODO: if function takes more than 7 args is usually bad analysis
if (max > 7) {
max = DEFAULT_MAX;
}
RVecString types;
RVecString_init (&types);
const int bytes = anal->config->bits / 8;
const ut32 opmask = R_ARCH_OP_MASK_BASIC | R_ARCH_OP_MASK_VAL | R_ARCH_OP_MASK_ESIL;
for (i = 0; i < max; i++) {
int arg_num = stack_rev? (max - 1 - i): i;
char *type = NULL;
const char *name = NULL;
R_LOG_DEBUG ("ARG NUM %d %d %d", i, arg_num, format);
if (format) {
if (RVecString_empty (&types)) {
break;
}
const String *type_ = RVecString_at (&types, pos++);
type = type_? strdup (*type_): NULL;
R_LOG_DEBUG ("TYPE (%s)", type);
} else {
type = r_type_func_args_type (TDB, fcn_name, arg_num);
name = r_type_func_args_name (TDB, fcn_name, arg_num);
}
if (!type && !userfnc) {
R_LOG_DEBUG ("NO TYPE AND NO USER FUNK");
continue;
}
if (!in_stack) {
// XXX: param arg_num must be fixed to support floating point register
// before this change place could be null
R_LOG_DEBUG ("not in stack");
const char *p = r_anal_cc_arg (anal, cc, arg_num, -1);
if (p && r_str_startswith (p, "stack")) {
in_stack = true;
place = p;
}
place = p;
}
char regname[REGNAME_SIZE] = { 0 };
ut64 xaddr = UT64_MAX;
int memref = 0;
bool cmt_set = false;
bool res = false;
bool memref_addr_valid = false;
ut64 memref_addr = UT64_MAX;
// Backtrace instruction from source sink to prev source sink
// Limit iterations to avoid quadratic blowup on large traces
const int bt_limit = R_MIN (idx - prev_idx + 1, TYPE_MATCH_MAX_BACKTRACE);
int bt_count = 0;
for (j = idx; j >= prev_idx && bt_count < bt_limit; j--, bt_count++) {
// r_strf_var (k, 32, "%d.addr", j);
// ut64 instr_addr = sdb_num_get (trace, k, 0);
ut64 instr_addr = etrace_addrof (tt, j);
R_LOG_DEBUG ("0x%08" PFMT64x " back traceing %d", instr_addr, j);
if (instr_addr < baddr) {
break;
}
RAnalOp *op = tp_anal_op (anal, instr_addr, opmask);
if (!op) {
break;
}
RAnalOp *next_op = tp_anal_op (anal, instr_addr + op->size, opmask);
if (!next_op || (j != idx && (next_op->type == R_ANAL_OP_TYPE_CALL || next_op->type == R_ANAL_OP_TYPE_JMP))) {
r_anal_op_free (op);
r_anal_op_free (next_op);
break;
}
RAnalVar *var = r_anal_get_used_function_var (anal, op->addr);
bool related = false;
const char *esil_str = r_strbuf_get (&op->esil);
if (esil_str) {
if (regname[0]) {
if (strstr (esil_str, regname)) {
related = true;
}
} else {
if (place && strstr (esil_str, place)) {
related = true;
}
if (!related && in_stack) {
ut64 sp = r_reg_getv (tps->tt.reg, "SP");
if (etrace_memread_contains_addr (tt, j, sp + size)) {
related = true;
}
}
}
}
// Match type from function param to instr
if (type_pos_hit (tps, in_stack, j, size, place)) {
R_LOG_DEBUG ("InHit");