-
-
Notifications
You must be signed in to change notification settings - Fork 367
/
fcn.c
2634 lines (2513 loc) · 82.5 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
// SPDX-FileCopyrightText: 2010-2021 nibble <[email protected]>
// SPDX-FileCopyrightText: 2010-2021 alvaro <[email protected]>
// SPDX-FileCopyrightText: 2010-2021 pancake <[email protected]>
// SPDX-License-Identifier: LGPL-3.0-only
#include <rz_analysis.h>
#include <rz_parse.h>
#include <rz_util.h>
#include <rz_list.h>
#define READ_AHEAD 1
#define SDB_KEY_BB "bb.0x%" PFMT64x ".0x%" PFMT64x
// XXX must be configurable by the user
#define JMPTBL_LEA_SEARCH_SZ 64
#define JMPTBL_MAXFCNSIZE 4096
#define BB_ALIGN 0x10
#define MAX_SCAN_SIZE 0x7ffffff
// 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)
#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__);
typedef struct fcn_tree_iter_t {
int len;
RBNode *cur;
RBNode *path[RZ_RBTREE_MAX_HEIGHT];
} FcnTreeIter;
RZ_API const char *rz_analysis_fcntype_tostring(int type) {
switch (type) {
case RZ_ANALYSIS_FCN_TYPE_NULL: return "null";
case RZ_ANALYSIS_FCN_TYPE_FCN: return "fcn";
case RZ_ANALYSIS_FCN_TYPE_LOC: return "loc";
case RZ_ANALYSIS_FCN_TYPE_SYM: return "sym";
case RZ_ANALYSIS_FCN_TYPE_IMP: return "imp";
case RZ_ANALYSIS_FCN_TYPE_INT: return "int"; // interrupt
case RZ_ANALYSIS_FCN_TYPE_ROOT: return "root";
}
return "unk";
}
#if READ_AHEAD
static ut64 cache_addr = UT64_MAX;
// TODO: move into io :?
static int read_ahead(RzAnalysis *analysis, 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 = analysis->iob.read_at(analysis->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 {
analysis->iob.read_at(analysis->iob.io, addr, cache, sizeof(cache));
memcpy(buf, cache, len);
cache_addr = addr;
}
return len;
}
#else
static int read_ahead(RzAnalysis *analysis, ut64 addr, ut8 *buf, int len) {
return analysis->iob.read_at(analysis->iob.io, addr, buf, len);
}
#endif
RZ_API void rz_analysis_fcn_invalidate_read_ahead_cache(void) {
#if READ_AHEAD
cache_addr = UT64_MAX;
#endif
}
static int cmpaddr(const void *_a, const void *_b) {
const RzAnalysisBlock *a = _a, *b = _b;
return a->addr > b->addr ? 1 : (a->addr < b->addr ? -1 : 0);
}
RZ_API int rz_analysis_function_resize(RzAnalysisFunction *fcn, int newsize) {
RzAnalysis *analysis = fcn->analysis;
RzAnalysisBlock *bb;
RzListIter *iter, *iter2;
rz_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 = analysis->cur->arch && !strncmp(analysis->cur->arch, "arm", 3);
if (is_arm) {
return true;
}
ut64 eof = fcn->addr + newsize;
rz_list_foreach_safe (fcn->bbs, iter, iter2, bb) {
if (bb->addr >= eof) {
rz_analysis_function_remove_block(fcn, bb);
continue;
}
if (bb->addr + bb->size >= eof) {
rz_analysis_block_set_size(bb, eof - bb->addr);
rz_analysis_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 RzAnalysisBlock *fcn_append_basic_block(RzAnalysis *analysis, RzAnalysisFunction *fcn, ut64 addr) {
RzAnalysisBlock *bb = rz_analysis_create_block(analysis, addr, 0);
if (!bb) {
return NULL;
}
rz_analysis_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 isInvalidMemory(RzAnalysis *analysis, const ut8 *buf, int len) {
if (analysis->opt.nonull > 0) {
int i;
const int count = RZ_MIN(len, analysis->opt.nonull);
for (i = 0; i < count; i++) {
if (buf[i]) {
break;
}
}
if (i == count) {
return true;
}
}
return !memcmp(buf, "\xff\xff\xff\xff", RZ_MIN(len, 4));
}
static bool isSymbolNextInstruction(RzAnalysis *analysis, RzAnalysisOp *op) {
rz_return_val_if_fail(analysis && op && analysis->flb.get_at, false);
RzFlagItem *fi = analysis->flb.get_at(analysis->flb.f, op->addr + op->size, false);
return (fi && fi->name && (strstr(fi->name, "imp.") || strstr(fi->name, "sym.") || strstr(fi->name, "entry") || strstr(fi->name, "main")));
}
static bool is_delta_pointer_table(RzAnalysis *analysis, RzAnalysisFunction *fcn, ut64 addr, ut64 lea_ptr, ut64 *jmptbl_addr, ut64 *casetbl_addr, RzAnalysisOp *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];
RzAnalysisOp *aop = jmp_aop;
RzAnalysisOp omov_aop = { 0 };
RzAnalysisOp mov_aop = { 0 };
RzAnalysisOp add_aop = { 0 };
RzRegItem *reg_src = NULL, *o_reg_dst = NULL;
RzAnalysisValue cur_scr, cur_dst = { 0 };
read_ahead(analysis, 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 = rz_analysis_op(analysis, aop, at, buf + i, left, RZ_ANALYSIS_OP_MASK_BASIC | RZ_ANALYSIS_OP_MASK_HINT | RZ_ANALYSIS_OP_MASK_VAL);
if (len < 1) {
len = 1;
}
if (aop->type == RZ_ANALYSIS_OP_TYPE_UJMP || aop->type == RZ_ANALYSIS_OP_TYPE_RJMP) {
isValid = true;
break;
} else if (aop->type == RZ_ANALYSIS_OP_TYPE_JMP || aop->type == RZ_ANALYSIS_OP_TYPE_CJMP) {
break;
}
if (aop->type == RZ_ANALYSIS_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 == RZ_ANALYSIS_OP_TYPE_ADD) {
add_aop = *aop;
}
rz_analysis_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(analysis, *jmptbl_addr, (ut8 *)&jmptbl, 64);
for (i = 0; i < 3; i++) {
dst = lea_ptr + (st32)rz_read_le32(jmptbl);
if (!analysis->iob.is_valid_offset(analysis->iob.io, dst, 0)) {
return false;
}
if (dst > fcn->addr + JMPTBL_MAXFCNSIZE) {
return false;
}
if (analysis->opt.jmpabove && dst < (fcn->addr < JMPTBL_MAXFCNSIZE ? 0 : fcn->addr - JMPTBL_MAXFCNSIZE)) {
return false;
}
}
return true;
}
static ut64 try_get_cmpval_from_parents(RzAnalysis *analysis, RzAnalysisFunction *fcn, RzAnalysisBlock *my_bb, const char *cmp_reg) {
rz_return_val_if_fail(fcn && fcn->bbs && cmp_reg, UT64_MAX);
RzListIter *iter;
RzAnalysisBlock *tmp_bb;
rz_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 == RZ_TYPE_COND_HI || tmp_bb->cond->type == RZ_TYPE_COND_GT) {
return tmp_bb->cmpval + 1;
}
}
return tmp_bb->cmpval;
}
}
}
return UT64_MAX;
}
static bool regs_exist(RzAnalysisValue *src, RzAnalysisValue *dst) {
rz_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(RzAnalysis *analysis, RzAnalysisFunction *fcn, RzAnalysisOp *op, RzAnalysisBlock *bb, ut64 addr,
char *tmp_buf, 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 (!analysis->flb.exist_at(analysis->flb.f, "skip", 4, addr)) {
snprintf(tmp_buf + 5, MAX_FLG_NAME_SIZE - 6, "%" PFMT64u, addr);
analysis->flb.set(analysis->flb.f, tmp_buf, addr, oplen);
fcn->addr += oplen;
rz_analysis_block_relocate(bb, bb->addr + oplen, bb->size - oplen);
*idx = un_idx;
return 1;
}
return 2;
}
return 0;
}
static bool purity_checked(HtUP *ht, RzAnalysisFunction *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, RzAnalysisFunction *fcn) {
RzListIter *iter;
RzList *xrefs = rz_analysis_function_get_xrefs_from(fcn);
RzAnalysisXRef *xref;
ht_up_insert(ht, fcn->addr, NULL);
fcn->is_pure = true;
rz_list_foreach (xrefs, iter, xref) {
if (xref->type == RZ_ANALYSIS_REF_TYPE_CALL || xref->type == RZ_ANALYSIS_REF_TYPE_CODE) {
RzAnalysisFunction *called_fcn = rz_analysis_get_fcn_in(fcn->analysis, xref->to, 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 (xref->type == RZ_ANALYSIS_REF_TYPE_DATA) {
fcn->is_pure = false;
break;
}
}
rz_list_free(xrefs);
}
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 RzAnalysisBlock *bbget(RzAnalysis *analysis, ut64 addr, bool jumpmid) {
RzList *intersecting = rz_analysis_get_blocks_in(analysis, addr);
RzListIter *iter;
RzAnalysisBlock *bb;
RzAnalysisBlock *ret = NULL;
rz_list_foreach (intersecting, iter, bb) {
ut64 eaddr = bb->addr + bb->size;
if (((bb->addr >= eaddr && addr == bb->addr) || rz_analysis_block_contains(bb, addr)) && (!jumpmid || rz_analysis_block_op_starts_at(bb, addr))) {
if (analysis->opt.delay) {
ut8 *buf = malloc(bb->size);
if (analysis->iob.read_at(analysis->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 = rz_analysis_block_get_op_offset(bb, i);
const ut64 at = bb->addr + off;
if (addr <= at || off >= bb->size) {
continue;
}
RzAnalysisOp op;
int size = rz_analysis_op(analysis, &op, at, buf + off, bb->size - off, RZ_ANALYSIS_OP_MASK_BASIC);
if (size > 0 && op.delay) {
if (op.delay >= last_instr_idx - i) {
in_delay_slot = true;
}
rz_analysis_op_fini(&op);
break;
}
rz_analysis_op_fini(&op);
}
if (in_delay_slot) {
free(buf);
continue;
}
}
free(buf);
}
ret = bb;
break;
}
}
rz_list_free(intersecting);
return ret;
}
typedef struct {
RzAnalysisFunction *fcn;
const int stack_diff;
} BlockTakeoverCtx;
static bool fcn_takeover_block_recursive_followthrough_cb(RzAnalysisBlock *block, void *user) {
BlockTakeoverCtx *ctx = user;
RzAnalysisFunction *our_fcn = ctx->fcn;
rz_analysis_block_ref(block);
while (!rz_list_empty(block->fcns)) {
RzAnalysisFunction *other_fcn = rz_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 = rz_analysis_block_get_op_addr(block, i);
RzPVector *vars_used = rz_analysis_function_get_vars_used_at(other_fcn, addr);
if (!vars_used) {
continue;
}
// vars_used will get modified if rz_analysis_var_remove_access_at gets called
RzPVector *cloned_vars_used = (RzPVector *)rz_vector_clone((RzVector *)vars_used);
void **it;
rz_pvector_foreach (cloned_vars_used, it) {
RzAnalysisVar *other_var = *it;
const int actual_delta = other_var->kind == RZ_ANALYSIS_VAR_KIND_SPV
? other_var->delta + ctx->stack_diff
: other_var->delta + (other_fcn->bp_off - our_fcn->bp_off);
RzAnalysisVar *our_var = rz_analysis_function_get_var(our_fcn, other_var->kind, actual_delta);
if (!our_var) {
our_var = rz_analysis_function_set_var(our_fcn, actual_delta, other_var->kind, other_var->type, 0, other_var->isarg, other_var->name);
}
if (our_var) {
RzAnalysisVarAccess *acc = rz_analysis_var_get_access_at(other_var, addr);
rz_analysis_var_set_access(our_var, acc->reg, addr, acc->type, acc->stackptr);
}
rz_analysis_var_remove_access_at(other_var, addr);
if (rz_vector_empty(&other_var->accesses)) {
rz_analysis_function_delete_var(other_fcn, other_var);
}
}
rz_pvector_free(cloned_vars_used);
}
// TODO: remove block->ninstr from other_fcn considering delay slots
rz_analysis_function_remove_block(other_fcn, block);
}
block->stackptr -= ctx->stack_diff;
block->parent_stackptr -= ctx->stack_diff;
rz_analysis_function_add_block(our_fcn, block);
// TODO: add block->ninstr from our_fcn considering delay slots
rz_analysis_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(RzAnalysisFunction *fcn, RzAnalysisBlock *start_block) {
BlockTakeoverCtx ctx = { fcn, start_block->parent_stackptr - fcn->stack };
rz_analysis_block_recurse_followthrough(start_block, fcn_takeover_block_recursive_followthrough_cb, &ctx);
}
static const char *retpoline_reg(RzAnalysis *analysis, ut64 addr) {
RzFlagItem *flag = analysis->flag_get(analysis->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(RzAnalysis *analysis, RzAnalysisOp *op) {
if (analysis->opt.retpoline) {
const char *rr = retpoline_reg(analysis, op->jump);
if (rr) {
op->type = RZ_ANALYSIS_OP_TYPE_RJMP;
op->reg = rr;
}
}
}
static inline bool op_is_set_bp(RzAnalysisOp *op, const char *bp_reg, const char *sp_reg) {
bool has_dst_reg = op->dst && op->dst->reg && op->dst->reg->name;
bool has_src_reg = op->src[0] && op->src[0]->reg && op->src[0]->reg->name;
if (has_dst_reg && has_src_reg) {
return !strcmp(bp_reg, op->dst->reg->name) && !strcmp(sp_reg, op->src[0]->reg->name);
}
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 int analyze_function_locally(RzAnalysis *analysis, RzAnalysisFunction *fcn, ut64 address) {
rz_return_val_if_fail(analysis && fcn, RZ_ANALYSIS_RET_ERROR);
RzVector tasks;
rz_vector_init(&tasks, sizeof(RzAnalysisTaskItem), NULL, NULL);
RzAnalysisTaskItem item = { fcn, NULL, fcn->stack, address };
rz_vector_push(&tasks, &item);
int saved_stack = fcn->stack; // TODO: DO NOT use fcn->stack to keep track of stack during analysis
int ret = rz_analysis_run_tasks(&tasks);
rz_vector_fini(&tasks);
fcn->stack = saved_stack;
return ret;
}
static inline void set_bb_branches(RZ_OUT RzAnalysisBlock *bb, const ut64 jump, const ut64 fail) {
bb->jump = jump;
bb->fail = fail;
}
/**
* \brief Analyses the given task item \p item for branches.
*
* Analysis starts for all instructions from \p item->start_address. If a branch is
* encountered a new task item is added to the list \p tasks.
* If an end of a basic function block is encountered (e.g. an invalid instruction),
* the cause for it is returned.
*
* \param item The task item with the parent function and start address to start analysing from.
* \param tasks The task list to append the new task items to.
* \return RzAnalysisBBEndCause Cause a basic block ended.
*/
static RzAnalysisBBEndCause run_basic_block_analysis(RzAnalysisTaskItem *item, RzVector *tasks) {
rz_return_val_if_fail(item && tasks, RZ_ANALYSIS_RET_ERROR);
RzAnalysis *analysis = item->fcn->analysis;
RzAnalysisFunction *fcn = item->fcn;
fcn->stack = item->stack;
ut64 addr = item->start_address;
ut64 len = analysis->opt.bb_max_size;
const int continue_after_jump = analysis->opt.afterjmp;
const int addrbytes = analysis->iob.io ? analysis->iob.io->addrbytes : 1;
char *last_reg_mov_lea_name = NULL;
char *movbasereg = NULL;
RzAnalysisBlock *bb = item->block;
RzAnalysisBlock *bbg = NULL;
RzAnalysisBBEndCause ret = RZ_ANALYSIS_RET_END, skip_ret = 0;
bool overlapped = false;
RzAnalysisOp op = { 0 };
int oplen, idx = 0;
int lea_cnt = 0;
static ut64 cmpval = UT64_MAX; // inherited across functions, otherwise it breaks :?
bool varset = false;
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(analysis->cur->arch);
bool is_arm = analysis->cur->arch && !strncmp(analysis->cur->arch, "arm", 3);
char tmp_buf[MAX_FLG_NAME_SIZE + 5] = "skip";
bool is_x86 = is_arm ? false : analysis->cur->arch && !strncmp(analysis->cur->arch, "x86", 3);
bool is_amd64 = is_x86 ? fcn->cc && !strcmp(fcn->cc, "amd64") : false;
bool is_dalvik = is_x86 ? false : analysis->cur->arch && !strncmp(analysis->cur->arch, "dalvik", 6);
bool is_hexagon = is_x86 ? false : analysis->cur->arch && !strncmp(analysis->cur->arch, "hexagon", 7);
RzRegItem *variadic_reg = NULL;
if (is_amd64) {
variadic_reg = rz_reg_get(analysis->reg, "rax", RZ_REG_TYPE_GPR);
}
bool has_variadic_reg = !!variadic_reg;
if (rz_cons_is_breaked()) {
rz_analysis_task_item_new(analysis, tasks, fcn, bb, addr);
return RZ_ANALYSIS_RET_END;
}
if (analysis->sleep) {
rz_sys_usleep(analysis->sleep);
}
// check if address is readable //:
if (!analysis->iob.is_valid_offset(analysis->iob.io, addr, 0)) {
if (addr != UT64_MAX && !analysis->iob.io->va) {
if (analysis->verbose) {
eprintf("Invalid address 0x%" PFMT64x ". Try with io.va=true\n", addr);
}
}
return RZ_ANALYSIS_RET_ERROR; // MUST BE TOO DEEP
}
RzAnalysisFunction *fcn_at_addr = rz_analysis_get_function_at(analysis, addr);
if (fcn_at_addr && fcn_at_addr != fcn) {
return RZ_ANALYSIS_RET_ERROR; // MUST BE NOT FOUND
}
if (!bb) {
RzAnalysisBlock *existing_bb = bbget(analysis, addr, analysis->opt.jmpmid && is_x86);
if (existing_bb) {
bool existing_in_fcn = rz_list_contains(existing_bb->fcns, fcn);
existing_bb = rz_analysis_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) {
rz_analysis_block_unref(existing_bb);
}
if (analysis->opt.recont) {
return RZ_ANALYSIS_RET_END;
}
if (analysis->verbose) {
eprintf("rz_analysis_fcn_bb() fails at 0x%" PFMT64x ".\n", addr);
}
return RZ_ANALYSIS_RET_ERROR; // MUST BE NOT DUP
}
item->block = bb = fcn_append_basic_block(analysis, fcn, addr);
// we checked before whether there is a bb at addr, so the create should have succeeded
rz_return_val_if_fail(bb, RZ_ANALYSIS_RET_ERROR);
}
if (!analysis->leaddrs) {
analysis->leaddrs = rz_list_newf(free_leaddr_pair);
if (!analysis->leaddrs) {
eprintf("Cannot create leaddr list\n");
gotoBeach(RZ_ANALYSIS_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 (analysis->limit && addr + idx < analysis->limit->from) {
gotoBeach(RZ_ANALYSIS_RET_END);
}
RzAnalysisFunction *tmp_fcn = rz_analysis_get_fcn_in(analysis, addr, 0);
if (tmp_fcn) {
// Checks if var is already analyzed at given addr
RzList *list = rz_analysis_var_all_list(analysis, tmp_fcn);
if (!rz_list_empty(list)) {
varset = true;
}
rz_list_free(list);
}
ut64 movdisp = UT64_MAX; // used by jmptbl when coded as "mov reg, [reg * scale + disp]"
ut64 movscale = 0;
ut8 buf[32]; // 32 bytes is enough to hold any instruction.
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(RZ_ANALYSIS_RET_END);
}
}
if ((maxlen - (addrbytes * idx)) > MAX_SCAN_SIZE) {
if (analysis->verbose) {
eprintf("Warning: Skipping large memory region.\n");
}
maxlen = 0;
}
while (addrbytes * idx < maxlen) {
ut32 at_delta;
ut64 at;
if (!last_is_reg_mov_lea) {
free(last_reg_mov_lea_name);
last_reg_mov_lea_name = NULL;
}
if (analysis->limit && analysis->limit->to <= addr + idx) {
break;
}
repeat:
at_delta = addrbytes * idx;
at = addr + at_delta;
if (rz_cons_is_breaked()) {
rz_analysis_task_item_new(analysis, tasks, fcn, bb, at);
break;
}
ut64 bytes_read = RZ_MIN(len - at_delta, sizeof(buf));
ret = read_ahead(analysis, at, buf, bytes_read);
if (ret < 0) {
eprintf("Failed to read\n");
break;
}
if (isInvalidMemory(analysis, buf, bytes_read)) {
if (analysis->verbose) {
eprintf("Warning: FFFF opcode at 0x%08" PFMT64x "\n", at);
}
gotoBeach(RZ_ANALYSIS_RET_ERROR)
}
rz_analysis_op_fini(&op);
if ((oplen = rz_analysis_op(analysis, &op, at, buf, bytes_read, RZ_ANALYSIS_OP_MASK_ESIL | RZ_ANALYSIS_OP_MASK_VAL | RZ_ANALYSIS_OP_MASK_HINT)) < 1) {
if (analysis->verbose) {
eprintf("Invalid instruction at 0x%" PFMT64x " with %d bits\n", at, analysis->bits);
}
// gotoBeach (RZ_ANALYSIS_RET_ERROR);
// RET_END causes infinite loops somehow
gotoBeach(RZ_ANALYSIS_RET_END);
}
const char *bp_reg = analysis->reg->name[RZ_REG_NAME_BP];
const char *sp_reg = analysis->reg->name[RZ_REG_NAME_SP];
bool has_stack_regs = bp_reg && sp_reg;
if (analysis->opt.nopskip && fcn->addr == at) {
RzFlagItem *fi = analysis->flb.get_at(analysis->flb.f, addr, false);
if (!fi || strncmp(fi->name, "sym.", 4)) {
if ((addr + delay.un_idx - oplen) == fcn->addr) {
if (rz_analysis_block_relocate(bb, bb->addr + oplen, bb->size - oplen)) {
fcn->addr += oplen;
idx = delay.un_idx;
goto repeat;
}
}
}
switch (op.type & RZ_ANALYSIS_OP_TYPE_MASK) {
case RZ_ANALYSIS_OP_TYPE_TRAP:
case RZ_ANALYSIS_OP_TYPE_ILL:
case RZ_ANALYSIS_OP_TYPE_NOP:
if (rz_analysis_block_relocate(bb, at + op.size, bb->size)) {
addr = at + op.size;
fcn->addr = addr;
goto repeat;
}
}
}
if (op.hint.new_bits) {
rz_analysis_hint_set_bits(analysis, op.jump, op.hint.new_bits);
}
if (idx > 0 && !overlapped) {
bbg = bbget(analysis, at, analysis->opt.jmpmid && is_x86);
if (bbg && bbg != bb) {
bb->jump = at;
if (analysis->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.
RzAnalysisBlock *split = rz_analysis_block_split(bbg, at);
rz_analysis_block_unref(split);
}
overlapped = true;
if (analysis->verbose) {
eprintf("Overlapped at 0x%08" PFMT64x "\n", at);
}
}
}
if (!overlapped) {
ut64 newbbsize = bb->size + oplen;
if (newbbsize > MAX_FCN_SIZE) {
gotoBeach(RZ_ANALYSIS_RET_ERROR);
}
rz_analysis_block_set_op_offset(bb, bb->ninstr++, at - bb->addr);
rz_analysis_block_set_size(bb, newbbsize);
fcn->ninstr++;
}
if (analysis->opt.trycatch) {
const char *name = analysis->coreb.getName(analysis->coreb.core, at);
if (name) {
if (rz_str_startswith(name, "try.") && rz_str_endswith(name, ".from")) {
char *handle = strdup(name);
// handle = rz_str_replace (handle, ".from", ".to", 0);
ut64 from_addr = analysis->coreb.numGet(analysis->coreb.core, handle);
handle = rz_str_replace(handle, ".from", ".catch", 0);
ut64 handle_addr = analysis->coreb.numGet(analysis->coreb.core, handle);
bb->jump = at + oplen;
if (from_addr != bb->addr) {
bb->fail = handle_addr;
ret = analyze_function_locally(analysis, fcn, handle_addr);
eprintf("(%s) 0x%08" PFMT64x "\n", handle, handle_addr);
if (bb->size == 0) {
rz_analysis_function_remove_block(fcn, bb);
}
rz_analysis_block_unref(bb);
bb = fcn_append_basic_block(analysis, fcn, addr);
if (!bb) {
gotoBeach(RZ_ANALYSIS_RET_ERROR);
}
}
}
}
}
idx += oplen;
delay.un_idx = idx;
if (analysis->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 (analysis->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 (analysis->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 (analysis->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) {
rz_analysis_block_set_size(bb, (ut64)addrbytes * (ut64)delay.after);
fcn->ninstr--;
if (analysis->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, rz_analysis_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
if (analysis->opt.vars && !varset) {
rz_analysis_extract_vars(analysis, fcn, &op);
}
if (has_stack_regs && arch_destroys_dst) {
if (op_is_set_bp(&op, bp_reg, sp_reg) && op.src[1]) {
switch (op.type & RZ_ANALYSIS_OP_TYPE_MASK) {
case RZ_ANALYSIS_OP_TYPE_ADD:
fcn->bp_off = fcn->stack - op.src[1]->imm;
break;
case RZ_ANALYSIS_OP_TYPE_SUB:
fcn->bp_off = fcn->stack + op.src[1]->imm;
break;
}
}
}
switch (op.stackop) {
case RZ_ANALYSIS_STACK_INC:
if (RZ_ABS(op.stackptr) < 8096) {
fcn->stack += op.stackptr;
if (fcn->stack > fcn->maxstack) {
fcn->maxstack = fcn->stack;
}
}
bb->stackptr += op.stackptr;
break;
case RZ_ANALYSIS_STACK_RESET:
bb->stackptr = 0;
break;
default:
break;
}
if (op.ptr && op.ptr != UT64_MAX && op.ptr != UT32_MAX) {
// swapped parameters
rz_analysis_xrefs_set(analysis, op.addr, op.ptr, RZ_ANALYSIS_REF_TYPE_DATA);
}
analyze_retpoline(analysis, &op);
switch (op.type & RZ_ANALYSIS_OP_TYPE_MASK) {
case RZ_ANALYSIS_OP_TYPE_CMOV:
case RZ_ANALYSIS_OP_TYPE_MOV:
last_is_reg_mov_lea = false;
if (is_arm) { // mov lr, pc
const char *esil = rz_strbuf_get(&op.esil);
if (!rz_str_cmp(esil, "pc,lr,=", -1)) {
last_is_mov_lr_pc = true;
}
}
if (has_stack_regs && op_is_set_bp(&op, 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 (analysis->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 {
RZ_FREE(movbasereg);
}
}
if (analysis->opt.hpskip && regs_exist(op.src[0], op.dst) && !strcmp(op.src[0]->reg->name, op.dst->reg->name)) {
skip_ret = skip_hp(analysis, fcn, &op, bb, addr, tmp_buf, oplen, delay.un_idx, &idx);
if (skip_ret == 1) {
goto repeat;
}
if (skip_ret == 2) {
gotoBeach(RZ_ANALYSIS_RET_END);
}
}
break;
case RZ_ANALYSIS_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 (op.ptr != UT64_MAX) {
leaddr_pair *pair = RZ_NEW(leaddr_pair);
if (!pair) {
eprintf("Cannot create leaddr_pair\n");
gotoBeach(RZ_ANALYSIS_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++;
rz_list_append(analysis->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;
}
}
// skip lea reg,[reg]
if (analysis->opt.hpskip && regs_exist(op.src[0], op.dst) && !strcmp(op.src[0]->reg->name, op.dst->reg->name)) {
skip_ret = skip_hp(analysis, fcn, &op, bb, at, tmp_buf, oplen, delay.un_idx, &idx);
if (skip_ret == 1) {
goto repeat;
}
if (skip_ret == 2) {
gotoBeach(RZ_ANALYSIS_RET_END);
}
}
if (analysis->opt.jmptbl) {
RzAnalysisOp jmp_aop = { 0 };
ut64 jmptbl_addr = op.ptr;
ut64 casetbl_addr = op.ptr;
if (is_delta_pointer_table(analysis, fcn, op.addr, op.ptr, &jmptbl_addr, &casetbl_addr, &jmp_aop)) {
// we require both checks here since rz_analysis_get_jmptbl_info uses
// BB info of the final jmptbl jump, which is no present with
// is_delta_pointer_table just scanning ahead
// rz_analysis_get_delta_jmptbl_info doesn't work at times where the
// lea comes after the cmp/default case cjmp, which can be
// handled with rz_analysis_get_jmptbl_info