/
fcn.c
2404 lines (2280 loc) · 71.7 KB
/
fcn.c
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 2010-2021 - nibble, alvaro, pancake */
#include <r_anal.h>
#include <r_parse.h>
#include <r_util.h>
#define READ_AHEAD 1
#define SDB_KEY_BB "bb.0x%"PFMT64x ".0x%"PFMT64x
// XXX must be configurable by the user
#define JMPTBLSZ 512
#define JMPTBL_LEA_SEARCH_SZ 64
#define JMPTBL_MAXFCNSIZE 4096
#define R_ANAL_MAX_INCSTACK 8096
#define BB_ALIGN 0x10
#define MAX_SCAN_SIZE 0x7ffffff
/* speedup analysis by removing some function overlapping checks */
#define JAYRO_04 1
// 16 KB is the maximum size for a basic block
#define MAX_FLG_NAME_SIZE 64
#define FIX_JMP_FWD 0
#define D if (a->verbose)
// 64KB max size
// 256KB max function size
#define MAX_FCN_SIZE (1024 * 256)
// Max NOP count to stop analysis
#define MAX_NOP_PREFIX_CNT 1024
#define DB a->sdb_fcns
#define EXISTS(x, ...) snprintf (key, sizeof (key) - 1, x, ## __VA_ARGS__), sdb_exists (DB, key)
#define SETKEY(x, ...) snprintf (key, sizeof (key) - 1, x, ## __VA_ARGS__);
R_API const char *r_anal_functiontype_tostring(int type) {
switch (type) {
case R_ANAL_FCN_TYPE_NULL: return "null";
case R_ANAL_FCN_TYPE_FCN: return "fcn";
case R_ANAL_FCN_TYPE_LOC: return "loc";
case R_ANAL_FCN_TYPE_SYM: return "sym";
case R_ANAL_FCN_TYPE_IMP: return "imp";
case R_ANAL_FCN_TYPE_INT: return "int"; // interrupt
case R_ANAL_FCN_TYPE_ROOT: return "root";
}
return "unk";
}
#if READ_AHEAD
static ut64 cache_addr = UT64_MAX;
// TODO: move into io :?
static int read_ahead(RAnal *anal, ut64 addr, ut8 *buf, int len) {
static ut8 cache[1024];
const int cache_len = sizeof (cache);
if (len < 1) {
return 0;
}
if (len > cache_len) {
int a = anal->iob.read_at (anal->iob.io, addr, buf, len); // double read
memcpy (cache, buf, cache_len);
cache_addr = addr;
return a;
}
ut64 addr_end = UT64_ADD_OVFCHK (addr, len)? UT64_MAX: addr + len;
ut64 cache_addr_end = UT64_ADD_OVFCHK (cache_addr, cache_len)? UT64_MAX: cache_addr + cache_len;
bool isCached = ((addr != UT64_MAX) && (addr >= cache_addr) && (addr_end < cache_addr_end));
if (isCached) {
memcpy (buf, cache + (addr - cache_addr), len);
} else {
anal->iob.read_at (anal->iob.io, addr, cache, sizeof (cache));
memcpy (buf, cache, len);
cache_addr = addr;
}
return len;
}
#else
static int read_ahead(RAnal *anal, ut64 addr, ut8 *buf, int len) {
return anal->iob.read_at (anal->iob.io, addr, buf, len);
}
#endif
R_API void r_anal_function_invalidate_read_ahead_cache(void) {
#if READ_AHEAD
cache_addr = UT64_MAX;
#endif
}
static int cmpaddr(const void *_a, const void *_b) {
const RAnalBlock *a = _a, *b = _b;
return a->addr > b->addr ? 1 : (a->addr < b->addr ? -1 : 0);
}
R_API int r_anal_function_resize(RAnalFunction *fcn, int newsize) {
RAnal *anal = fcn->anal;
RAnalBlock *bb;
RListIter *iter, *iter2;
r_return_val_if_fail (fcn, false);
if (newsize < 1) {
return false;
}
// XXX this is something we should probably do for all the archs
bool is_arm = anal->cur->arch && !strncmp (anal->cur->arch, "arm", 3);
if (is_arm) {
return true;
}
ut64 eof = fcn->addr + newsize;
r_list_foreach_safe (fcn->bbs, iter, iter2, bb) {
if (bb->addr >= eof) {
r_anal_function_remove_block (fcn, bb);
continue;
}
if (bb->addr + bb->size >= eof) {
r_anal_block_set_size (bb, eof - bb->addr);
r_anal_block_update_hash (bb);
}
if (bb->jump != UT64_MAX && bb->jump >= eof) {
bb->jump = UT64_MAX;
}
if (bb->fail != UT64_MAX && bb->fail >= eof) {
bb->fail = UT64_MAX;
}
}
return true;
}
// Create a new 0-sized basic block inside the function
static RAnalBlock *fcn_append_basic_block(RAnal *anal, RAnalFunction *fcn, ut64 addr) {
RAnalBlock *bb = r_anal_create_block (anal, addr, 0);
if (!bb) {
return NULL;
}
r_anal_function_add_block (fcn, bb);
bb->stackptr = fcn->stack;
bb->parent_stackptr = fcn->stack;
return bb;
}
#define gotoBeach(x) ret = x; goto beach;
static bool is_invalid_memory(RAnal *anal, const ut8 *buf, int len) {
if (anal->opt.nonull > 0) {
int i;
const int count = R_MIN (len, anal->opt.nonull);
for (i = 0; i < count; i++) {
if (buf[i]) {
break;
}
}
if (i == count) {
return true;
}
}
return !memcmp (buf, "\xff\xff\xff\xff", R_MIN (len, 4));
}
static bool is_symbol_flag(const char *name) {
return strstr (name, "imp.")
|| strstr (name, "dbg.")
|| strstr (name, "sym.")
|| !strncmp (name, "entry", 5)
|| !strcmp (name, "main");
}
static bool next_instruction_is_symbol(RAnal *anal, RAnalOp *op) {
r_return_val_if_fail (anal && op && anal->flb.get_at, false);
RFlagItem *fi = anal->flb.get_at (anal->flb.f, op->addr + op->size, false);
return (fi && fi->name && is_symbol_flag (fi->name));
}
static bool is_delta_pointer_table(RAnal *anal, RAnalFunction *fcn, ut64 addr, ut64 lea_ptr, ut64 *jmptbl_addr, ut64 *casetbl_addr, RAnalOp *jmp_aop) {
int i;
ut64 dst;
st32 jmptbl[64] = {0};
/* check if current instruction is followed by an ujmp */
ut8 buf[JMPTBL_LEA_SEARCH_SZ];
RAnalOp *aop = jmp_aop;
RAnalOp omov_aop = {0};
RAnalOp mov_aop = {0};
RAnalOp add_aop = {0};
RRegItem *reg_src = NULL, *o_reg_dst = NULL;
RAnalValue cur_scr, cur_dst = {0};
read_ahead (anal, addr, (ut8*)buf, sizeof (buf));
bool isValid = false;
for (i = 0; i + 8 < JMPTBL_LEA_SEARCH_SZ; i++) {
ut64 at = addr + i;
int left = JMPTBL_LEA_SEARCH_SZ - i;
int len = r_anal_op (anal, aop, at, buf + i, left, R_ANAL_OP_MASK_BASIC | R_ANAL_OP_MASK_HINT | R_ANAL_OP_MASK_VAL);
if (len < 1) {
len = 1;
}
if (aop->type == R_ANAL_OP_TYPE_UJMP || aop->type == R_ANAL_OP_TYPE_RJMP) {
isValid = true;
break;
}
if (aop->type == R_ANAL_OP_TYPE_JMP || aop->type == R_ANAL_OP_TYPE_CJMP) {
break;
}
if (aop->type == R_ANAL_OP_TYPE_MOV) {
omov_aop = mov_aop;
mov_aop = *aop;
o_reg_dst = cur_dst.reg;
if (mov_aop.dst) {
cur_dst = *mov_aop.dst;
}
if (mov_aop.src[0]) {
cur_scr = *mov_aop.src[0];
reg_src = cur_scr.regdelta;
}
}
if (aop->type == R_ANAL_OP_TYPE_ADD) {
add_aop = *aop;
}
r_anal_op_fini (aop);
i += len - 1;
}
if (!isValid) {
return false;
}
// check if we have a msvc 19xx style jump table using rva table entries
// lea reg1, [base_addr]
// mov reg2, dword [reg1 + tbl_off*4 + tbl_loc_off]
// add reg2, reg1
// jmp reg2
if (mov_aop.type && add_aop.type && mov_aop.addr < add_aop.addr && add_aop.addr < jmp_aop->addr
&& mov_aop.disp && mov_aop.disp != UT64_MAX) {
// disp in this case should be tbl_loc_off
*jmptbl_addr += mov_aop.disp;
if (o_reg_dst && reg_src && o_reg_dst->offset == reg_src->offset && omov_aop.disp != UT64_MAX) {
// Special case for indirection
// lea reg1, [base_addr]
// movzx reg2, byte [reg1 + tbl_off + casetbl_loc_off]
// mov reg3, dword [reg1 + reg2*4 + tbl_loc_off]
// add reg3, reg1
// jmp reg3
*casetbl_addr += omov_aop.disp;
}
}
#if 0
// required for the last jmptbl.. but seems to work without it and breaks other tests
if (mov_aop.type && mov_aop.ptr) {
*jmptbl_addr += mov_aop.ptr;
// absjmptbl
lea_ptr = mov_aop.ptr;
}
#endif
/* check if jump table contains valid deltas */
read_ahead (anal, *jmptbl_addr, (ut8 *)&jmptbl, 64);
for (i = 0; i < 3; i++) {
dst = lea_ptr + (st32)r_read_le32 (jmptbl);
if (!anal->iob.is_valid_offset (anal->iob.io, dst, 0)) {
return false;
}
if (dst > fcn->addr + JMPTBL_MAXFCNSIZE) {
return false;
}
if (anal->opt.jmpabove && dst < (fcn->addr < JMPTBL_MAXFCNSIZE ? 0 : fcn->addr - JMPTBL_MAXFCNSIZE)) {
return false;
}
}
return true;
}
static ut64 try_get_cmpval_from_parents(RAnal *anal, RAnalFunction *fcn, RAnalBlock *my_bb, const char *cmp_reg) {
if (!cmp_reg) {
if (anal->verbose) {
eprintf ("try_get_cmpval_from_parents: cmp_reg not defined.\n");
}
return UT64_MAX;
}
r_return_val_if_fail (fcn && fcn->bbs, UT64_MAX);
RListIter *iter;
RAnalBlock *tmp_bb;
r_list_foreach (fcn->bbs, iter, tmp_bb) {
if (tmp_bb->jump == my_bb->addr || tmp_bb->fail == my_bb->addr) {
if (tmp_bb->cmpreg == cmp_reg) {
if (tmp_bb->cond) {
if (tmp_bb->cond->type == R_ANAL_COND_HI || tmp_bb->cond->type == R_ANAL_COND_GT) {
return tmp_bb->cmpval + 1;
}
}
return tmp_bb->cmpval;
}
}
}
return UT64_MAX;
}
static bool regs_exist(RAnalValue *src, RAnalValue *dst) {
r_return_val_if_fail (src && dst, false);
return src->reg && dst->reg && src->reg->name && dst->reg->name;
}
// 0 if not skipped; 1 if skipped; 2 if skipped before
static int skip_hp(RAnal *anal, RAnalFunction *fcn, RAnalOp *op, RAnalBlock *bb, ut64 addr, int oplen, int un_idx, int *idx) {
// this step is required in order to prevent infinite recursion in some cases
if ((addr + un_idx - oplen) == fcn->addr) {
// use addr instead of op->addr to mark repeat
if (!anal->flb.exist_at (anal->flb.f, "skip", 4, addr)) {
char *name = r_str_newf ("skip.%"PFMT64x, addr);
anal->flb.set (anal->flb.f, name, addr, oplen);
free (name);
fcn->addr += oplen;
r_anal_block_relocate (bb, bb->addr + oplen, bb->size - oplen);
*idx = un_idx;
return 1;
}
return 2;
}
return 0;
}
static bool purity_checked(HtUP *ht, RAnalFunction *fcn) {
bool checked;
ht_up_find (ht, fcn->addr, &checked);
return checked;
}
/*
* Checks whether a given function is pure and sets its 'is_pure' field.
* This function marks fcn 'not pure' if fcn, or any function called by fcn, accesses data
* from outside, even if it only READS it.
* Probably worth changing it in the future, so that it marks fcn 'impure' only when it
* (or any function called by fcn) MODIFIES external data.
*/
static void check_purity(HtUP *ht, RAnalFunction *fcn) {
RListIter *iter;
RList *refs = r_anal_function_get_refs (fcn);
RAnalRef *ref;
ht_up_insert (ht, fcn->addr, NULL);
fcn->is_pure = true;
r_list_foreach (refs, iter, ref) {
if (ref->type == R_ANAL_REF_TYPE_CALL || ref->type == R_ANAL_REF_TYPE_CODE) {
RAnalFunction *called_fcn = r_anal_get_fcn_in (fcn->anal, ref->addr, 0);
if (!called_fcn) {
continue;
}
if (!purity_checked (ht, called_fcn)) {
check_purity (ht, called_fcn);
}
if (!called_fcn->is_pure) {
fcn->is_pure = false;
break;
}
}
if (ref->type == R_ANAL_REF_TYPE_DATA) {
fcn->is_pure = false;
break;
}
}
r_list_free (refs);
}
typedef struct {
ut64 op_addr;
ut64 leaddr;
char *reg;
} leaddr_pair;
static void free_leaddr_pair(void *pair) {
leaddr_pair *_pair = pair;
free (_pair->reg);
free (_pair);
}
static RAnalBlock *bbget(RAnal *anal, ut64 addr, bool jumpmid) {
RList *intersecting = r_anal_get_blocks_in (anal, addr);
RListIter *iter;
RAnalBlock *bb;
RAnalBlock *ret = NULL;
r_list_foreach (intersecting, iter, bb) {
ut64 eaddr = bb->addr + bb->size;
if (((bb->addr >= eaddr && addr == bb->addr)
|| r_anal_block_contains (bb, addr))
&& (!jumpmid || r_anal_block_op_starts_at (bb, addr))) {
if (anal->opt.delay) {
ut8 *buf = malloc (bb->size);
if (anal->iob.read_at (anal->iob.io, bb->addr, buf, bb->size)) {
const int last_instr_idx = bb->ninstr - 1;
bool in_delay_slot = false;
int i;
for (i = last_instr_idx; i >= 0; i--) {
const ut64 off = r_anal_bb_offset_inst (bb, i);
const ut64 at = bb->addr + off;
if (addr <= at || off >= bb->size) {
continue;
}
RAnalOp op;
int size = r_anal_op (anal, &op, at, buf + off, bb->size - off, R_ANAL_OP_MASK_BASIC);
if (size > 0 && op.delay) {
if (op.delay >= last_instr_idx - i) {
in_delay_slot = true;
}
r_anal_op_fini (&op);
break;
}
r_anal_op_fini (&op);
}
if (in_delay_slot) {
free (buf);
continue;
}
}
free (buf);
}
ret = bb;
break;
}
}
r_list_free (intersecting);
return ret;
}
typedef struct {
RAnalFunction *fcn;
const int stack_diff;
} BlockTakeoverCtx;
static bool fcn_takeover_block_recursive_followthrough_cb(RAnalBlock *block, void *user) {
BlockTakeoverCtx *ctx = user;
RAnalFunction *our_fcn = ctx->fcn;
r_anal_block_ref (block);
while (!r_list_empty (block->fcns)) {
RAnalFunction *other_fcn = r_list_first (block->fcns);
if (other_fcn->addr == block->addr) {
return false;
}
// Steal vars from this block
size_t i;
for (i = 0; i < block->ninstr; i++) {
const ut64 addr = r_anal_bb_opaddr_i (block, i);
RPVector *vars_used = r_anal_function_get_vars_used_at (other_fcn, addr);
if (!vars_used) {
continue;
}
// vars_used will get modified if r_anal_var_remove_access_at gets called
RPVector *cloned_vars_used = (RPVector *)r_vector_clone ((RVector *)vars_used);
void **it;
r_pvector_foreach (cloned_vars_used, it) {
RAnalVar *other_var = *it;
const int actual_delta = other_var->kind == R_ANAL_VAR_KIND_SPV
? other_var->delta + ctx->stack_diff
: other_var->delta + (other_fcn->bp_off - our_fcn->bp_off);
RAnalVar *our_var = r_anal_function_get_var (our_fcn, other_var->kind, actual_delta);
if (!our_var) {
our_var = r_anal_function_set_var (our_fcn, actual_delta, other_var->kind, other_var->type, 0, other_var->isarg, other_var->name);
}
if (our_var) {
RAnalVarAccess *acc = r_anal_var_get_access_at (other_var, addr);
r_anal_var_set_access (our_var, acc->reg, addr, acc->type, acc->stackptr);
}
r_anal_var_remove_access_at (other_var, addr);
if (r_vector_empty (&other_var->accesses)) {
r_anal_function_delete_var (other_fcn, other_var);
}
}
r_pvector_free (cloned_vars_used);
}
// TODO: remove block->ninstr from other_fcn considering delay slots
r_anal_function_remove_block (other_fcn, block);
}
block->stackptr -= ctx->stack_diff;
block->parent_stackptr -= ctx->stack_diff;
r_anal_function_add_block (our_fcn, block);
// TODO: add block->ninstr from our_fcn considering delay slots
r_anal_block_unref (block);
return true;
}
// Remove block and all of its recursive successors from all its functions and add them only to fcn
static void fcn_takeover_block_recursive(RAnalFunction *fcn, RAnalBlock *start_block) {
BlockTakeoverCtx ctx = { fcn, start_block->parent_stackptr - fcn->stack};
r_anal_block_recurse_followthrough (start_block, fcn_takeover_block_recursive_followthrough_cb, &ctx);
}
static const char *retpoline_reg(RAnal *anal, ut64 addr) {
RFlagItem *flag = anal->flag_get (anal->flb.f, addr);
if (flag) {
const char *token = "x86_indirect_thunk_";
const char *thunk = strstr (flag->name, token);
if (thunk) {
return thunk + strlen (token);
}
}
#if 0
// TODO: implement following code analysis check for stripped binaries:
// 1) op(addr).type == CALL
// 2) call_dest = op(addr).addr
// 3) op(call_dest).type == STORE
// 4) op(call_dest + op(call_dest).size).type == RET
[0x00000a65]> pid 6
0x00000a65 sym.__x86_indirect_thunk_rax:
0x00000a65 .------- e807000000 call 0xa71
0x00000a6a | f390 pause
0x00000a6c | 0faee8 lfence
0x00000a6f | ebf9 jmp 0xa6a
0x00000a71 `----> 48890424 mov qword [rsp], rax
0x00000a75 c3 ret
#endif
return NULL;
}
static void analyze_retpoline(RAnal *anal, RAnalOp *op) {
if (anal->opt.retpoline) {
const char *rr = retpoline_reg (anal, op->jump);
if (rr) {
op->type = R_ANAL_OP_TYPE_RJMP;
op->reg = rr;
}
}
}
static inline bool op_is_set_bp(const char *op_dst, const char *op_src, const char *bp_reg, const char *sp_reg) {
if (op_dst && op_src) {
return !strcmp (bp_reg, op_dst) && !strcmp (sp_reg, op_src);
}
return false;
}
static inline bool does_arch_destroys_dst(const char *arch) {
return arch && (!strncmp (arch, "arm", 3) || !strcmp (arch, "riscv") || !strcmp (arch, "ppc"));
}
static inline bool has_vars(RAnal *anal, ut64 addr) {
RAnalFunction *tmp_fcn = r_anal_get_fcn_in (anal, addr, 0);
if (tmp_fcn) {
return r_anal_var_count_all (tmp_fcn) > 0;
}
return false;
}
static int fcn_recurse(RAnal *anal, RAnalFunction *fcn, ut64 addr, ut64 len, int depth) {
char *bp_reg = NULL;
char *sp_reg = NULL;
char *op_dst = NULL;
char *op_src = NULL;
if (depth < 1) {
if (anal->verbose) {
eprintf ("Too deep fcn_recurse at 0x%"PFMT64x "\n", addr);
}
return R_ANAL_RET_ERROR; // MUST BE TOO DEEP
}
// TODO Store all this stuff in the heap so we save memory in the stack
RAnalOp *op = NULL;
char *movbasereg = NULL;
const int addrbytes = anal->iob.io ? anal->iob.io->addrbytes : 1;
char *last_reg_mov_lea_name = NULL;
RAnalBlock *bb = NULL;
RAnalBlock *bbg = NULL;
int ret = R_ANAL_RET_END, skip_ret = 0;
bool overlapped = false;
int oplen, idx = 0;
size_t lea_cnt = 0;
size_t nop_prefix_cnt = 0;
static ut64 cmpval = UT64_MAX; // inherited across functions, otherwise it breaks :?
struct {
int cnt;
int idx;
int after;
int pending;
int adjust;
int un_idx; // delay.un_idx
} delay = {
0
};
bool arch_destroys_dst = does_arch_destroys_dst (anal->cur->arch);
const bool is_arm = anal->cur->arch && !strncmp (anal->cur->arch, "arm", 3);
const bool is_v850 = is_arm ? false: (anal->cur->arch && (!strncmp (anal->cur->arch, "v850", 4) || !strncmp (anal->coreb.cfgGet (anal->coreb.core, "asm.cpu"), "v850", 4)));
const bool is_x86 = is_arm ? false: anal->cur->arch && !strncmp (anal->cur->arch, "x86", 3);
const bool is_amd64 = is_x86 ? fcn->cc && !strcmp (fcn->cc, "amd64") : false;
const bool is_dalvik = is_x86 ? false : anal->cur->arch && !strncmp (anal->cur->arch, "dalvik", 6);
RRegItem *variadic_reg = NULL;
if (is_amd64) {
variadic_reg = r_reg_get (anal->reg, "rax", R_REG_TYPE_GPR);
}
bool has_variadic_reg = !!variadic_reg;
if (r_cons_is_breaked ()) {
return R_ANAL_RET_END;
}
if (anal->sleep) {
r_sys_usleep (anal->sleep);
}
// check if address is readable //:
if (!anal->iob.is_valid_offset (anal->iob.io, addr, 0)) {
if (addr != UT64_MAX && !anal->iob.io->va) {
if (anal->verbose) {
eprintf ("Invalid address 0x%"PFMT64x ". Try with io.va=true\n", addr);
}
}
return R_ANAL_RET_ERROR; // MUST BE TOO DEEP
}
RAnalFunction *fcn_at_addr = r_anal_get_function_at (anal, addr);
if (fcn_at_addr && fcn_at_addr != fcn) {
return R_ANAL_RET_ERROR; // MUST BE NOT FOUND
}
RAnalBlock *existing_bb = bbget (anal, addr, anal->opt.jmpmid && is_x86);
if (existing_bb) {
bool existing_in_fcn = r_list_contains (existing_bb->fcns, fcn);
existing_bb = r_anal_block_split (existing_bb, addr);
if (!existing_in_fcn && existing_bb) {
if (existing_bb->addr == fcn->addr) {
// our function starts directly there, so we steal what is ours!
fcn_takeover_block_recursive (fcn, existing_bb);
}
}
if (existing_bb) {
r_anal_block_unref (existing_bb);
}
if (anal->opt.recont) {
return R_ANAL_RET_END;
}
if (anal->verbose) {
eprintf ("r_anal_function_bb() fails at 0x%"PFMT64x "\n", addr);
}
return R_ANAL_RET_ERROR; // MUST BE NOT DUP
}
bb = fcn_append_basic_block (anal, fcn, addr);
// we checked before whether there is a bb at addr, so the create should have succeeded
r_return_val_if_fail (bb, R_ANAL_RET_ERROR);
if (!anal->leaddrs) {
anal->leaddrs = r_list_newf (free_leaddr_pair);
if (!anal->leaddrs) {
eprintf ("Cannot create leaddr list\n");
gotoBeach (R_ANAL_RET_ERROR);
}
}
static ut64 lea_jmptbl_ip = UT64_MAX;
ut64 last_reg_mov_lea_val = UT64_MAX;
bool last_is_reg_mov_lea = false;
bool last_is_push = false;
bool last_is_mov_lr_pc = false;
ut64 last_push_addr = UT64_MAX;
if (anal->limit && addr + idx < anal->limit->from) {
gotoBeach (R_ANAL_RET_END);
}
bool varset = has_vars (anal, addr); // Checks if var is already analyzed at given addr
ut64 movdisp = UT64_MAX; // used by jmptbl when coded as "mov Reg,[Reg*Scale+Disp]"
ut64 movscale = 0;
int maxlen = len * addrbytes;
if (is_dalvik) {
bool skipAnalysis = false;
if (!strncmp (fcn->name, "sym.", 4)) {
if (!strncmp (fcn->name + 4, "imp.", 4)) {
skipAnalysis = true;
} else if (strstr (fcn->name, "field")) {
skipAnalysis = true;
}
}
if (skipAnalysis) {
gotoBeach (R_ANAL_RET_END);
}
}
if ((maxlen - (addrbytes * idx)) > MAX_SCAN_SIZE) {
if (anal->verbose) {
eprintf ("Warning: Skipping large memory region.\n");
}
maxlen = 0;
}
const char *_bp_reg = anal->reg->name[R_REG_NAME_BP];
const char *_sp_reg = anal->reg->name[R_REG_NAME_SP];
const bool has_stack_regs = _bp_reg && _sp_reg;
if (has_stack_regs) {
bp_reg = strdup (_bp_reg);
sp_reg = strdup (_sp_reg);
}
op = r_anal_op_new ();
while (addrbytes * idx < maxlen) {
if (!last_is_reg_mov_lea) {
free (last_reg_mov_lea_name);
last_reg_mov_lea_name = NULL;
}
if (anal->limit && anal->limit->to <= addr + idx) {
break;
}
repeat:
if (r_cons_is_breaked ()) {
break;
}
ut8 buf[32]; // 32 bytes is enough to hold any instruction.
ut32 at_delta = addrbytes * idx;
ut64 at = addr + at_delta;
ut64 bytes_read = R_MIN (len - at_delta, sizeof (buf));
ret = read_ahead (anal, at, buf, bytes_read);
if (ret < 0) {
eprintf ("Failed to read\n");
break;
}
if (is_invalid_memory (anal, buf, bytes_read)) {
if (anal->verbose) {
eprintf ("Warning: FFFF opcode at 0x%08"PFMT64x "\n", at);
}
gotoBeach (R_ANAL_RET_ERROR)
}
r_anal_op_fini (op);
if ((oplen = r_anal_op (anal, op, at, buf, bytes_read, R_ANAL_OP_MASK_ESIL | R_ANAL_OP_MASK_VAL | R_ANAL_OP_MASK_HINT)) < 1) {
if (anal->verbose) {
eprintf ("Invalid instruction at 0x%"PFMT64x" with %d bits\n", at, anal->bits);
}
// gotoBeach (R_ANAL_RET_ERROR);
// RET_END causes infinite loops somehow
gotoBeach (R_ANAL_RET_END);
}
free (op_dst);
op_dst = (op->dst && op->dst->reg && op->dst->reg->name)? strdup (op->dst->reg->name): NULL;
free (op_src);
op_src = (op->src[0] && op->src[0]->reg && op->src[0]->reg->name) ? strdup (op->src[0]->reg->name): NULL;
if (anal->opt.nopskip && fcn->addr == at) {
RFlagItem *fi = anal->flb.get_at (anal->flb.f, addr, false);
if (!fi || strncmp (fi->name, "sym.", 4)) {
if ((addr + delay.un_idx - oplen) == fcn->addr) {
if (r_anal_block_relocate (bb, bb->addr + oplen, bb->size - oplen)) {
fcn->addr += oplen;
idx = delay.un_idx;
goto repeat;
}
}
}
switch (op->type & R_ANAL_OP_TYPE_MASK) {
case R_ANAL_OP_TYPE_TRAP:
case R_ANAL_OP_TYPE_ILL:
case R_ANAL_OP_TYPE_NOP:
nop_prefix_cnt++;
if (nop_prefix_cnt > MAX_NOP_PREFIX_CNT) {
gotoBeach (R_ANAL_RET_ERROR);
}
if (r_anal_block_relocate (bb, at + op->size, bb->size)) {
addr = at + op->size;
fcn->addr = addr;
goto repeat;
}
}
}
if (op->hint.new_bits) {
r_anal_hint_set_bits (anal, op->jump, op->hint.new_bits);
}
if (idx > 0 && !overlapped) {
bbg = bbget (anal, at, anal->opt.jmpmid && is_x86);
if (bbg && bbg != bb) {
bb->jump = at;
if (anal->opt.jmpmid && is_x86) {
// This happens when we purposefully walked over another block and overlapped it
// and now we hit an offset where the instructions match again.
// So we need to split the overwalked block.
RAnalBlock *split = r_anal_block_split (bbg, at);
r_anal_block_unref (split);
}
overlapped = true;
if (anal->verbose) {
eprintf ("Overlapped at 0x%08"PFMT64x "\n", at);
}
}
}
if (!overlapped) {
const ut64 newbbsize = bb->size + oplen;
if (newbbsize > MAX_FCN_SIZE) {
gotoBeach (R_ANAL_RET_ERROR);
}
r_anal_bb_set_offset (bb, bb->ninstr++, at - bb->addr);
r_anal_block_set_size (bb, newbbsize);
fcn->ninstr++;
}
if (anal->opt.trycatch) {
const char *name = anal->coreb.getName (anal->coreb.core, at);
if (name) {
if (r_str_startswith (name, "try.") && r_str_endswith (name, ".from")) {
char *handle = strdup (name);
// handle = r_str_replace (handle, ".from", ".to", 0);
ut64 from_addr = anal->coreb.numGet (anal->coreb.core, handle);
handle = r_str_replace (handle, ".from", ".catch", 0);
ut64 handle_addr = anal->coreb.numGet (anal->coreb.core, handle);
bb->jump = at + oplen;
if (from_addr != bb->addr) {
bb->fail = handle_addr;
ret = r_anal_function_bb (anal, fcn, handle_addr, depth - 1);
eprintf ("(%s) 0x%08"PFMT64x"\n", handle, handle_addr);
if (bb->size == 0) {
r_anal_function_remove_block (fcn, bb);
}
r_anal_block_unref (bb);
bb = fcn_append_basic_block (anal, fcn, addr);
if (!bb) {
gotoBeach (R_ANAL_RET_ERROR);
}
}
}
}
}
idx += oplen;
delay.un_idx = idx;
if (anal->opt.delay && op->delay > 0 && !delay.pending) {
// Handle first pass through a branch delay jump:
// Come back and handle the current instruction later.
// Save the location of it in `delay.idx`
// note, we have still increased size of basic block
// (and function)
if (anal->verbose) {
eprintf ("Enter branch delay at 0x%08"PFMT64x ". bb->sz=%"PFMT64u"\n", at - oplen, bb->size);
}
delay.idx = idx - oplen;
delay.cnt = op->delay;
delay.pending = 1; // we need this in case the actual idx is zero...
delay.adjust = !overlapped; // adjustment is required later to avoid double count
continue;
}
if (delay.cnt > 0) {
// if we had passed a branch delay instruction, keep
// track of how many still to process.
delay.cnt--;
if (!delay.cnt) {
if (anal->verbose) {
eprintf ("Last branch delayed opcode at 0x%08"PFMT64x ". bb->sz=%"PFMT64u"\n", addr + idx - oplen, bb->size);
}
delay.after = idx;
idx = delay.idx;
// At this point, we are still looking at the
// last instruction in the branch delay group.
// Next time, we will again be looking
// at the original instruction that entered
// the branch delay.
}
} else if (op->delay > 0 && delay.pending) {
if (anal->verbose) {
eprintf ("Revisit branch delay jump at 0x%08"PFMT64x ". bb->sz=%"PFMT64u"\n", addr + idx - oplen, bb->size);
}
// This is the second pass of the branch delaying opcode
// But we also already counted this instruction in the
// size of the current basic block, so we need to fix that
if (delay.adjust) {
r_anal_block_set_size (bb, (ut64)addrbytes * (ut64)delay.after);
fcn->ninstr--;
if (anal->verbose) {
eprintf ("Correct for branch delay @ %08"PFMT64x " bb.addr=%08"PFMT64x " corrected.bb=%"PFMT64u" f.uncorr=%"PFMT64u"\n",
addr + idx - oplen, bb->addr, bb->size, r_anal_function_linear_size (fcn));
}
}
// Next time, we go to the opcode after the delay count
// Take care not to use this below, use delay.un_idx instead ...
idx = delay.after;
delay.pending = delay.after = delay.idx = delay.adjust = 0;
}
// Note: if we got two branch delay instructions in a row due to an
// compiler bug or junk or something it wont get treated as a delay
switch (op->stackop) {
case R_ANAL_STACK_INC:
if (R_ABS (op->stackptr) < R_ANAL_MAX_INCSTACK) {
fcn->stack += op->stackptr;
if (fcn->stack > fcn->maxstack) {
fcn->maxstack = fcn->stack;
}
}
bb->stackptr += op->stackptr;
break;
case R_ANAL_STACK_RESET:
bb->stackptr = 0;
break;
default:
break;
}
if (op->ptr && op->ptr != UT64_MAX && op->ptr != UT32_MAX) {
// swapped parameters wtf
r_anal_xrefs_set (anal, op->addr, op->ptr, R_ANAL_REF_TYPE_DATA);
}
if (anal->opt.vars && !varset) {
// XXX uses op.src/dst and fails because regprofile invalidates the regitems
// lets just call this BEFORE retpoline() to avoid such issue
r_anal_extract_vars (anal, fcn, op);
}
// this call may cause regprofile changes which cause ranalop.regitem references to be invalid
analyze_retpoline (anal, op);
switch (op->type & R_ANAL_OP_TYPE_MASK) {
case R_ANAL_OP_TYPE_CMOV:
case R_ANAL_OP_TYPE_MOV:
last_is_reg_mov_lea = false;
if (is_arm) { // mov lr, pc
const char *esil = r_strbuf_get (&op->esil);
if (!r_str_cmp (esil, "pc,lr,=", -1)) {
last_is_mov_lr_pc = true;
}
}
if (has_stack_regs && op_is_set_bp (op_dst, op_src, bp_reg, sp_reg)) {
fcn->bp_off = fcn->stack;
}
// Is this a mov of immediate value into a register?
if (op->dst && op->dst->reg && op->dst->reg->name && op->val > 0 && op->val != UT64_MAX) {
free (last_reg_mov_lea_name);
if ((last_reg_mov_lea_name = strdup (op->dst->reg->name))) {
last_reg_mov_lea_val = op->val;
last_is_reg_mov_lea = true;
}
}
// skip mov reg, reg
if (anal->opt.jmptbl && op->scale && op->ireg) {
movdisp = op->disp;
movscale = op->scale;
if (op->src[0] && op->src[0]->reg) {
free (movbasereg);
movbasereg = strdup (op->src[0]->reg->name);
} else {
R_FREE (movbasereg);
}
}
if (anal->opt.hpskip && regs_exist (op->src[0], op->dst) && !strcmp (op->src[0]->reg->name, op->dst->reg->name)) {
skip_ret = skip_hp (anal, fcn, op, bb, addr, oplen, delay.un_idx, &idx);
if (skip_ret == 1) {
goto repeat;
}
if (skip_ret == 2) {
gotoBeach (R_ANAL_RET_END);
}
}
break;
case R_ANAL_OP_TYPE_LEA:
last_is_reg_mov_lea = false;
// if first byte in op->ptr is 0xff, then set leaddr assuming its a jumptable
#if 0
{
ut8 buf[4];
anal->iob.read_at (anal->iob.io, op->ptr, buf, sizeof (buf));
if ((buf[2] == 0xff || buf[2] == 0xfe) && buf[3] == 0xff) {
leaddr_pair *pair = R_NEW (leaddr_pair);
if (!pair) {
eprintf ("Cannot create leaddr_pair\n");
gotoBeach (R_ANAL_RET_ERROR);
}
pair->op_addr = op->addr;
pair->leaddr = op->ptr; // XXX movdisp is dupped but seems to be trashed sometimes(?), better track leaddr separately
r_list_append (anal->leaddrs, pair);
}
if (has_stack_regs && op_is_set_bp (op, bp_reg, sp_reg)) {
fcn->bp_off = fcn->stack - op->src[0]->delta;
}
if (op->dst && op->dst->reg && op->dst->reg->name && op->ptr > 0 && op->ptr != UT64_MAX) {
free (last_reg_mov_lea_name);
if ((last_reg_mov_lea_name = strdup (op->dst->reg->name))) {
last_reg_mov_lea_val = op->ptr;
last_is_reg_mov_lea = true;
}
}
#else
if (op->ptr != UT64_MAX) {
leaddr_pair *pair = R_NEW (leaddr_pair);
if (!pair) {
eprintf ("Cannot create leaddr_pair\n");
gotoBeach (R_ANAL_RET_ERROR);
}
pair->op_addr = op->addr;
pair->leaddr = op->ptr; // XXX movdisp is dupped but seems to be trashed sometimes(?), better track leaddr separately
pair->reg = op->reg
? strdup (op->reg)
: op->dst && op->dst->reg
? strdup (op->dst->reg->name)
: NULL;
lea_cnt++;
r_list_append (anal->leaddrs, pair);
}
if (has_stack_regs && op_is_set_bp (op_dst, op_src, bp_reg, sp_reg) ) {
fcn->bp_off = fcn->stack - op->src[0]->delta;
}
if (op->dst && op->dst->reg && op->dst->reg->name && op->ptr > 0 && op->ptr != UT64_MAX) {
free (last_reg_mov_lea_name);
if ((last_reg_mov_lea_name = strdup(op->dst->reg->name))) {
last_reg_mov_lea_val = op->ptr;
last_is_reg_mov_lea = true;
}
}
#endif
// skip lea reg,[reg]
if (anal->opt.hpskip && regs_exist (op->src[0], op->dst)
&& !strcmp (op->src[0]->reg->name, op->dst->reg->name)) {
skip_ret = skip_hp (anal, fcn, op, bb, at, oplen, delay.un_idx, &idx);
if (skip_ret == 1) {
goto repeat;
}
if (skip_ret == 2) {
gotoBeach (R_ANAL_RET_END);
}
}
if (anal->opt.jmptbl) {