-
Notifications
You must be signed in to change notification settings - Fork 29
/
decompiler.cpp
4481 lines (4350 loc) · 211 KB
/
decompiler.cpp
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
/**
* @file idaplugin/decompiler.cpp
* @brief Module contains classes/methods dealing with program decompilation.
* @copyright (c) 2019 Gregory Morse, licensed under the MIT license
*/
//linux build test - need C++14 however
//AWS: sudo yum -y groupinstall "Development Tools"
//g++ -std=c++1y -m64 -I include -I . -D__IDP__ -D__PLUGIN__ -DNO_OBSOLETE_FUNCS -D__X64__ -D__LINUX__ -fpermissive GhidraDecIface.cpp
//relative registers?
//graph AST view - need to return the full XML info or some custom graph data structure?
#define _CRT_SECURE_NO_WARNINGS
#include <algorithm>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <set>
#include <sstream>
#include <memory>
#include "retdec/utils/os.h"
#include "code_viewer.h"
#include "decompiler.h"
#include "plugin_config.h"
#include <fixup.hpp>
#include <entry.hpp>
#include <segment.hpp>
#include "sleighinterface.h"
#if !defined(OS_WINDOWS)
//cpp -dM <<<'' | grep 'FLT_'
#define FLT_DECIMAL_DIG __FLT_DECIMAL_DIG__
#define DBL_DECIMAL_DIG __DBL_DECIMAL_DIG__
#endif
#define min(x, y) ((x <= y) ? (x) : (y))
using namespace retdec;
namespace idaplugin {
//types depend on types - circular only through structure resolved by forward declarations
//function declarations depend on types
//data depends on types and other data or functions due to pointers - circular resolved by extern keyword
//function definitions depend on types and data - circular resolved by function declaration
//add core types
//problems in following table with calculation of pointer sizes - default/near/far
;
/*const size_t sizeTable[] = { //-1 means unknown/not allowed/need to parse for more information
-1, 0, sizeof(__int8), sizeof(__int16), sizeof(__int32), sizeof(__int64), 16, inf.cc.size_i,
inf.cc.size_b, sizeof(float), ph.max_ptr_size() - ph.segreg_size, -1, -1, -1, -1, -1,
2, 1, sizeof(__int8), sizeof(__int16), sizeof(__int32), sizeof(__int64), 16, inf.cc.size_i,
1, sizeof(double), ph.max_ptr_size() - ph.segreg_size, -1, -1, -1, -1, -1,
8, 4, sizeof(__int8), sizeof(__int16), sizeof(__int32), sizeof(__int64), 16, inf.cc.size_i,
inf_is_64bit() ? 8 : 2, inf.cc.size_ldbl, ph.max_ptr_size(), -1, -1, inf.cc.size_e, -1, -1,
-1, 16, sizeof(char), -1, -1, -1, -1, ph.segreg_size,
4, ph.use_tbyte() ? ph.tbyte_size : 2, -1, -1, -1, -1, -1, -1 };*/
template <class T>
std::string to_string(T t, std::ios_base& (__cdecl* f)(std::ios_base&))
{
std::ostringstream oss;
oss << f << t;
return oss.str();
}
unsigned long long addrToOffset(std::string space, unsigned long long offset)
{
if (space == "ram") return offset;
//else if (space == "stack")
//else if (space == "register")
//else if (space == "join")
else return 0;
}
std::string getMetaTypeInfo(const tinfo_t& ti)
{
if (ti.is_void()) return "void";
else if (ti.is_char() || is_type_int(ti.get_realtype()) && ti.is_signed()) return "int";
else if (is_type_int(ti.get_realtype())) return "uint"; //is_unsigned() || get_sign() == no_sign
else if (ti.is_floating()) return "float";
else if (ti.is_bool()) return "bool";
else if (ti.is_udt()) return "struct"; //ti.is_struct() || ti.is_union()
else if (ti.is_array()) return "array";
else if (ti.is_func() || ti.is_funcptr()) return "code";
else if (ti.is_ptr() /*|| ti.is_array() && ti.get_size() == 0*/) return "ptr";
else if (ti.is_enum()) return ti.is_signed() ? "int" : "uint"; //"int" if BTE_SDEC?
else return "unknown";
}
bool isX86()
{
std::string procName = inf_procname;
return procName == "8086" ||
procName == "8086r" ||
procName == "8086p" ||
procName == "k62" ||
procName == "athlon" ||
procName == "80386p"
|| procName == "80386r"
|| procName == "80486p"
|| procName == "80486r"
|| procName == "80586p"
|| procName == "80586r"
|| procName == "80686p"
|| procName == "p2"
|| procName == "p3"
|| procName == "p4"
|| procName == "metapc";
}
std::string ccToStr(cm_t c, int callMethod, bool bInit)
{
//if (!bInit && c == inf_cc_cm) return "default"; //&& ccToStr(inf_cc_cm, is_code_far(inf_cc_cm) ? FTI_FARCALL : FTI_NEARCALL, true) == modelDefault //if this default is not used its meaningless here
if (!inf_is_32bit() && !inf_is_64bit() && isX86() && ((c & CM_CC_MASK) == CM_CC_STDCALL || (c & CM_CC_MASK) == CM_CC_PASCAL || (c & CM_CC_MASK) == CM_CC_CDECL)) {//16-bit x86 code needs right model
std::string model;
if ((c & CM_CC_MASK) == CM_CC_STDCALL || (c & CM_CC_MASK) == CM_CC_PASCAL) model = "__stdcall";
else model = "__cdecl";
model += "16"; // && is_code_far(inf_cc_cm)
model += (callMethod == FTI_FARCALL || callMethod == FTI_DEFCALL && is_code_far(c)) ? "far" : "near"; //|| (c & (CM_MASK | CM_M_MASK)) == (CM_UNKNOWN | CM_M_NN)
return model;
}
//if (!bInit && (c & CM_CC_MASK) == (inf_cc_cm & CM_CC_MASK)) return "default";
switch (c & CM_CC_MASK) {
case CM_CC_FASTCALL: return !inf_is_32bit() && !inf_is_64bit() ? "__regcall" : "__fastcall"; //return "__vectorcall"; - extension to fastcall
case CM_CC_STDCALL: return "__stdcall";
case CM_CC_VOIDARG: return "__cdecl";
case CM_CC_CDECL: return "__cdecl";
case CM_CC_THISCALL: return "__thiscall";
case CM_CC_PASCAL: return "__stdcall"; // "__pascal";
case CM_CC_ELLIPSIS: return "__cdecl";
case CM_CC_SPECIAL: return "__cdecl";
case CM_CC_SPECIALE: return "__cdecl";
case CM_CC_SPECIALP: return "__stdcall";
case CM_CC_UNKNOWN: default: return "unknown";
}
}
bool getFuncByGuess(ea_t ea, tinfo_t& ti)
{
if (get_tinfo(&ti, ea) && ti.is_func()) return true;
tinfo_t tryti;
if (guess_tinfo(&tryti, ea) != GUESS_FUNC_OK) return false;
ti = tryti;
return true;
}
IdaCallback::~IdaCallback() {
if (decInt != nullptr) delete decInt;
if (sendfp != nullptr) qfclose(sendfp);
if (recvfp != nullptr) qfclose(recvfp);
if (recfp != nullptr) qfclose(recfp);
}
int IdaCallback::EnumImportNames(ea_t ea, const char* name, uval_t ord, void* param)
{
(*((ImportParam*)param)->pImports)[ea] = ImportInfo{ name == nullptr ? "" : name, ord, ((ImportParam*)param)->cur };
return 1;
}
int IdaCallback::regNameToIndexIda(std::string regstr) {
int res = decInt->regNameToIndex(regstr);
if (res == -1 && *regstr.begin() == '$') {
res = decInt->regNameToIndex(regstr.substr(1));
}
return res;
}
std::string IdaCallback::arglocToAddr(argloc_t al, unsigned long long* offset, std::vector<SizedAddrInfo>& joins, bool noResolveReg) {
if (al.is_ea()) {
*offset = al.get_ea();
return "ram";
} else if (al.is_stkoff()) {
*offset = al.stkoff();
return "stack";
} else if (al.is_scattered()) {
scattered_aloc_t scat;
for (size_t i = scat.size() - 1; i != -1; i--) { //these appear to be high to low, so need to reverse order here
unsigned long long offs;
std::vector<SizedAddrInfo> j; //can have a register reg1() as the is_mixed_scattered indicates
std::string spc = arglocToAddr(scat[i], &offs, j, false); //all "ram" - certainly join or reg2 would not make sense
joins.push_back(SizedAddrInfo{ {spc, scat[i].off}, scat[i].size });
}
return "join";
} else if (al.is_reg1()) {
//qstring qs;
//get_reg_name(&qs, al.reg1(), size);
//al.regoff() == 0; //how to handle register bit offset?
bitrange_t bits;
const char* regnm = get_reg_info(ph.reg_names[al.reg1()], &bits); //use default processor name
reg_info_t ri;
parse_reg_name(&ri, regnm == nullptr ? ph.reg_names[al.reg1()] : regnm);
qstring qs;
get_reg_name(&qs, al.reg1(), ri.size);
*offset = noResolveReg ? -1 : regNameToIndexIda(qs.c_str());
return "register";
} else if (al.is_reg2()) {
//qstring qs1, qs2;
//get_reg_name(&qs1, al.reg1(), size);
//get_reg_name(&qs2, al.reg2(), size);
//*offset = regNameToIndexIda(ph.reg_names[al.reg1()]);
bitrange_t bits1, bits2;
const char* regnm1 = get_reg_info(ph.reg_names[al.reg1()], &bits1),
* regnm2 = get_reg_info(ph.reg_names[al.reg2()], &bits2); //use default processor name
reg_info_t ri1, ri2;
parse_reg_name(&ri1, regnm1 == nullptr ? ph.reg_names[al.reg1()] : regnm1);
parse_reg_name(&ri2, regnm2 == nullptr ? ph.reg_names[al.reg2()] : regnm2);
qstring qs1, qs2;
get_reg_name(&qs1, al.reg1(), ri1.size);
get_reg_name(&qs2, al.reg2(), ri2.size);
//reg2 is the high value, as in dx for pair dx:ax, so it needs to be added to the join space first
joins.push_back(SizedAddrInfo{ {"register", noResolveReg ? -1 : (unsigned long long)regNameToIndexIda(qs2.c_str())}, (unsigned long long)ri2.size });
joins.push_back(SizedAddrInfo{ {"register", noResolveReg ? -1 : (unsigned long long)regNameToIndexIda(qs1.c_str())}, (unsigned long long)ri1.size });
return "join";
} else if (al.is_rrel()) {
*offset = al.get_rrel().off; //some type of spacebase
bitrange_t bits;
const char* regnm = get_reg_info(ph.reg_names[al.get_rrel().reg], &bits); //use default processor name
reg_info_t ri;
parse_reg_name(&ri, regnm == nullptr ? ph.reg_names[al.get_rrel().reg] : regnm);
qstring qs;
get_reg_name(&qs, al.get_rrel().reg, ri.size);
int regidx = regNameToIndexIda(ph.reg_names[al.get_rrel().reg]);
return decInt->regToSpacebase(regidx);
}
//al.is_custom() || al.is_badloc();
*offset = 0;
return "ram";
}
void IdaCallback::launchDecompiler()
{
if (PRINT_DEBUG) {
sendfp = qfopen("d:/source/repos/ghidradec/tests/written", "wb");
recvfp = qfopen("d:/source/repos/ghidradec/tests/received", "wb");
recfp = qfopen("d:/source/repos/ghidradec/tests/protorec", "wb");
}
runCommand(di->decCmd, "",
&di->decompPid, &di->hDecomp, &di->rdHandle, &di->wrHandle,
true);
}
size_t IdaCallback::readDec(void* Buf, size_t MaxCharCount)
{
size_t val = _read(di->rdHandle, Buf, (unsigned int)MaxCharCount);
if (recvfp != nullptr) qfwrite(recvfp, Buf, MaxCharCount);
return val;
//return qpipe_read(di->rdHandle, Buf, MaxCharCount);
}
size_t IdaCallback::writeDec(void const* Buf, size_t MaxCharCount)
{
if (sendfp != nullptr) qfwrite(sendfp, Buf, MaxCharCount);
return _write(di->wrHandle, Buf, (unsigned int)MaxCharCount);
//return qpipe_write(di->wrHandle, Buf, MaxCharCount);
}
void IdaCallback::protocolRecorder(std::string data, bool bWrite)
{
if (recfp != nullptr) {
std::string s = ((bWrite ? "Sent: " : "Received: ") + data + "\n");
qfwrite(recfp, s.c_str(), s.size());
}
}
void IdaCallback::terminate()
{
if (sendfp != nullptr) { qfclose(sendfp); sendfp = nullptr; }
if (recvfp != nullptr) { qfclose(recvfp); recvfp = nullptr; }
if (recfp != nullptr) { qfclose(recfp); recfp = nullptr; }
stopDecompilation(di, false, false, false);
}
void IdaCallback::getInits(std::vector<InitStateItem>& inits)
{
//inf_start_ea == ea; inf.start_ss; inf.start_sp;
if (ph.has_segregs()) { //initialize segment registers for tracking - vital for x86-16
//code segment register although a pointless mapping helps track things for Ghidra
unsigned long long regtrans = (unsigned long long)regNameToIndexIda(ph.reg_names[ph.reg_code_sreg]);
for (int j = 0; j < get_segm_qty(); j++) {
segment_t* s = getnseg(j);
if (s != nullptr) {
qstring qs;
if (get_segm_class(&qs, s) != -1 && qs == "CODE") {
inits.push_back(InitStateItem{ {"ram", s->start_ea}, {"ram", s->end_ea}, {{"register", regtrans}, (unsigned long)ph.segreg_size}, (unsigned long long)s->sel });
}
}
}
for (int i = 0; i <= ph.reg_last_sreg - ph.reg_first_sreg; i++) {
regtrans = (unsigned long long)regNameToIndexIda(ph.reg_names[i + ph.reg_first_sreg]);
if (regtrans == -1) continue;
//this is a much more powerful analysis by the processor engine than the default segregs which now are not used
for (size_t k = 0; k < sregRanges[i].size(); k++) {
if (sregRanges[i][k].val == -1) continue;
//if (out.val == ((1 << (ph.segreg_size * 8)) - 1)) continue;
inits.push_back(InitStateItem{ {"ram", sregRanges[i][k].start_ea}, {"ram", sregRanges[i][k].end_ea}, {{"register", regtrans}, (unsigned long)ph.segreg_size}, (unsigned long long)sregRanges[i][k].val });
}
//if (s->defsr[i] != -1) {
//inits.push_back(InitStateItem{ "ram", s->start_ea, "ram", s->end_ea, "register", (unsigned long long)regNameToIndexIda(ph.reg_names[i + ph.reg_first_sreg]), (unsigned long)ph.segreg_size, (unsigned long long)s->defsr[i] });
//}
}
}
}
std::string IdaCallback::getPcodeInject(int type, std::string name, AddrInfo addr, std::string fixupbase, unsigned long long fixupoffset)
{
if (type == DecompInterface::CALLMECHANISM_TYPE) {
if ((name == "__stdcall16far@@inject_uponreturn" || name == "__cdecl16far@@inject_uponreturn") && addr.space == "ram") {
sel_t s;
executeOnMainThread([&s, addr]() { s = getseg((ea_t)addr.offset)->sel; });
return "CS = " + std::to_string(s) + ";";
} else return "";
} else return "";
}
void IdaCallback::getCPoolRef(const std::vector<unsigned long long>& refs, CPoolRecord& rec)
{
}
#define CACHEPAGESIZE 4096ull
#define CACHELIMIT 128
#define CACHECLEANUPAFTER 256
int IdaCallback::getBytes(unsigned char* ptr, int size, AddrInfo addr)
{
int i = 0;
if (addr.space == "ram") {
if (byteCache.size() > CACHECLEANUPAFTER) {
for (std::map<ea_t, std::pair<unsigned long long, std::vector<unsigned short>>>::iterator it = byteCache.begin(); it != byteCache.end();) {
if (it->second.first < cacheCount - CACHELIMIT) it = byteCache.erase(it);
else it++;
}
}
//paging strategy for easy lookup - just like the processor utilizes
bool bFetch = false;
unsigned long long page = addr.offset & (~(CACHEPAGESIZE - 1)),
pgoffs = addr.offset & (CACHEPAGESIZE - 1);
do {
if (byteCache.find((ea_t)page) == byteCache.end()) {
bFetch = true;
break;
}
page += CACHEPAGESIZE;
} while (page < addr.offset + size);
if (bFetch) executeOnMainThread([this, size, addr]() {
unsigned long long page = addr.offset & (~(CACHEPAGESIZE - 1));
do {
for (int i = 0; i < CACHEPAGESIZE; i++) { //i = offset & (CACHEPAGESIZE - 1);
byteCache[(ea_t)page].second.push_back(is_loaded((ea_t)page + i) ? get_byte((ea_t)page + i) : 256);
}
page += CACHEPAGESIZE;
} while (page < addr.offset + size);
});
page = addr.offset & (~(CACHEPAGESIZE - 1));
pgoffs = addr.offset & (CACHEPAGESIZE - 1);
byteCache[(ea_t)page].first = cacheCount++;
for (i = 0; i < size; i++) {
if (pgoffs == CACHEPAGESIZE) {
page += CACHEPAGESIZE;
pgoffs = 0;
byteCache[(ea_t)page].first = cacheCount++;
}
if ((byteCache[(ea_t)page].second[(size_t)pgoffs] & 256) == 0) ptr[i] = (unsigned char)byteCache[(ea_t)page].second[(size_t)pgoffs];
else break; //could do something like 0x90 for NOP on x86 - but could be data request
pgoffs++;
}
}
if (i != size) memset(ptr + i, 0, size - i);
//msg("%0X%0X%0X%0X %0X%0X%0X%0X\n", ptr[0], ptr[1], ptr[2], ptr[3], ptr[4], ptr[5], ptr[6], ptr[7]);
return i;
}
std::string getSymbolName(unsigned long long offset)
{
std::string str = get_name((ea_t)offset).c_str();
if (str.size() == 0) {
str = to_string(offset, std::hex);
str = ("ram0x" + std::string((inf_is_64bit() ? 16 : 8) - str.size(), '0') + str);
}
return str;
}
void getMemoryInfo(unsigned long long offset, bool* readonly, bool* volatil)
{
*volatil = !is_mapped((ea_t)offset);
segment_t* s = getseg((ea_t)offset);
//(s->type & SEG_DATA) != 0;
*readonly = s != nullptr && (s->perm & SEGPERM_WRITE) == 0 && (s->perm & SEGPERM_MAXVAL) != 0;
xrefblk_t xr;
if (xr.first_to((ea_t)offset, XREF_ALL)) {
do {
if ((xr.type & XREF_MASK) == dr_W) {
*readonly = false;
}
} while (xr.next_to());
}
}
void IdaCallback::getFuncInfo(AddrInfo addr, func_t* f, std::string& name, FuncProtoInfo& func)
{
//get_ea_name(&qs, offset, GN_VISIBLE | GN_DEMANGLED | GN_SHORT);
if (imports.find((ea_t)addr.offset) != imports.end() && imports[(ea_t)addr.offset].name != "") {
name = demangle_name(imports[(ea_t)addr.offset].name.c_str(), MNG_SHORT_FORM).c_str();
if (name.size() == 0) name = imports[(ea_t)addr.offset].name;
}
if (name.size() == 0) name = get_short_name((ea_t)addr.offset, GN_STRICT).c_str();
if (name.size() != 0) name = name.substr(0, name.find("(", 0));
else name = getSymbolName(addr.offset);
func.isInline = false;
bool bFuncTinfo = getFuncTypeInfoByAddr(f != nullptr ? f->start_ea : (ea_t)addr.offset, func);
func.isNoReturn = (f != nullptr) ? !f->does_return() : (bFuncTinfo ? func.isNoReturn : false);// f->flags& FUNC_NORET ? true : false;
//(f->flags & FUNC_USERFAR) != 0
//(f->flags & FUNC_LIB) != 0
//(f->flags & FUNC_STATICDEF) != 0
size_t curArgs = func.syminfo.size();
if (f != nullptr) {
if (func.model == "unknown") {
if (f->argsize == 0) { //|| !f->does_return()
func.model = ccToStr((f->flags & FUNC_PURGED_OK) != 0 ? CM_CC_CDECL : CM_CC_UNKNOWN, f->is_far() || (f->flags & FUNC_USERFAR) != 0 ? FTI_FARCALL : FTI_NEARCALL, false);
} else { //CM_CC_UNKNOWN is likely better...
func.model = ccToStr(CM_CC_STDCALL, f->is_far() || (f->flags & FUNC_USERFAR) != 0 ? FTI_FARCALL : FTI_NEARCALL, false);
}
}
if (func.extraPop == -1 && (f->flags & FUNC_PURGED_OK) != 0) func.extraPop = (unsigned long long)f->argsize; //type unknown but have frame so now can calculate
if (f->regargs == nullptr) read_regargs(f); //populates regargs, similar to how get_spd or the like with f specified populate stkpts
//callregs_t cr;
//cr.init_regs(inf_cc_cm);
for (int i = 0; i < f->regargqty; i++) { //name can be a nullptr!
std::string nm = f->regargs[i].name == nullptr ? "" : f->regargs[i].name;
unsigned long long offset;
std::vector<TypeInfo> typeChain;
unsigned long long size;
//func_type_data_t ftd;
//if (ti.is_func() && ti.get_func_details(&ftd)) {
//callregs_t cr;
//ph.get_cc_regs(&cr, get_cc(ftd.get_cc()));
if (f->regargs[i].type != nullptr) {
tinfo_t ti; //The type information is internally kept as an array of bytes terminated by 0.
qtype typeForDeser;
typeForDeser.append(f->regargs[i].type);
ti.deserialize(get_idati(), &typeForDeser); //will free buffer passed!
getType(ti, typeChain, false);
size = ti.get_size();
qstring qs;
if (get_reg_name(&qs, f->regargs[i].reg, (size_t)size) == -1) offset = -1; //for example 1 byte of DS register will fail
else offset = regNameToIndexIda(qs.c_str());
if (offset == -1) {
bitrange_t bits;
const char* regnm = nullptr;
regnm = get_reg_info(ph.reg_names[f->regargs[i].reg], &bits); //use default processor name
offset = regNameToIndexIda(regnm == nullptr ? ph.reg_names[f->regargs[i].reg] : regnm);
}
} else {
bitrange_t bits;
const char* regnm = nullptr;
regnm = get_reg_info(ph.reg_names[f->regargs[i].reg], &bits); //use default processor name
reg_info_t ri;
parse_reg_name(&ri, regnm == nullptr ? ph.reg_names[f->regargs[i].reg] : regnm);
size = ri.size;
qstring qs;
get_reg_name(&qs, f->regargs[i].reg, ri.size);
offset = regNameToIndexIda(qs.c_str());
}
if (offset == -1) {
offset = regNameToIndexIda(ph.reg_names[f->regargs[i].reg]); //last try if nothing else works
if (offset == -1) continue;
}
std::vector<SymInfo>::iterator it = nm.empty() ? func.syminfo.end() : std::find_if(func.syminfo.begin(), func.syminfo.end(), [&nm](SymInfo it) { return it.pi.name == nm; });
if (it == func.syminfo.end()) {
it = std::find_if(func.syminfo.begin(), func.syminfo.end(), [offset](SymInfo it) { return it.pi.name == "" && it.addr.addr.space == "register" && it.addr.addr.offset == offset; });
}
if (it != func.syminfo.end()) {
if (it->pi.name == "") it->pi.name = nm;
it->addr.addr.space = "register";
it->addr.addr.offset = offset;
continue;
}
if (f->regargs[i].type == nullptr) {
std::string metaType = "unknown";
int typ = DecompInterface::coreTypeLookup((int)size, metaType);
if (typ == -1 && size != 1) {
typeChain.push_back(TypeInfo{ "", (unsigned long long)size, "array", false, false, false, (unsigned long long)size });
typeChain.push_back(TypeInfo{ "undefined", 1, metaType });
} else {
typeChain.push_back(TypeInfo{ typ == -1 ? "undefined" : defaultCoreTypes[typ].name, (unsigned long long)size, metaType });
}
coreTypeUsed[typ == -1 ? 1 : typ] = true;
}
func.syminfo.push_back(SymInfo{ { nm, typeChain }, {{"register", offset}, size}, (int)curArgs++ });
}
}
if (f != nullptr && f->frame != BADNODE) { //f->analyzed_sp()
struc_t* frame = get_frame(f);
func.extraPop += get_frame_retsize(f);
ea_t firstarg = frame_off_args(f);
//generalized for any arguments not found in the frame
for (size_t i = 0; i < func.syminfo.size(); i++) {
if (func.syminfo[i].addr.addr.space == "stack") {
func.syminfo[i].addr.addr.offset += firstarg - frame_off_retaddr(f);
}
}
for (uint32 i = 0; i < frame->memqty; i++) {
//if (frame->members[i].get_soff() >= f->frsize && bFuncTinfo) break; //args already read for type info but offsets not adjusted
//" r" for return address and " s" for saved registers is a convention that seems to be used in IDA
if (!(is_funcarg_off(f, frame->members[i].get_soff()) || lvar_off(f, frame->members[i].get_soff()))) continue;
std::string nm = get_member_name(frame->members[i].id).c_str();
if (frame_off_retaddr(f) == frame->members[i].get_soff()) continue;
/*if (nm == " r") {
retSize = get_member_size(&frame->members[i]);
continue;
}*/
if (frame_off_savregs(f) == frame->members[i].get_soff()) continue;
//if (nm == " s") continue;
std::vector<SymInfo>::iterator it = nm.empty() ? func.syminfo.end() : std::find_if(func.syminfo.begin(), func.syminfo.end(), [&nm](SymInfo it) { return it.pi.name == nm; });
unsigned long long offset = frame->members[i].soff - frame_off_retaddr(f);// - firstarg;
if (it == func.syminfo.end()) {
//if no name, offset is from 0, so use arg offset
//msg("Offset: %llX\n", offset);
it = std::find_if(func.syminfo.begin(), func.syminfo.end(), [offset](SymInfo it) { return it.pi.name == "" && it.addr.addr.space == "stack" && it.addr.addr.offset == offset; });
}
//unsigned long long reloffs = frame->members[i].get_soff() - frame_off_retaddr(f); // - f->frsize - f->frregs; //frame seems to always be relative to return address
if (it != func.syminfo.end()) {
if (it->pi.name == "") it->pi.name = nm;
it->addr.addr.space = "stack";
it->addr.addr.offset = offset;
continue;
}
//if (frame->members[i].get_soff() >= f->frsize && frame->members[i].get_soff() < f->frsize + 1 + f->frregs) continue; //return address size is computed how - get_member_size() for " r"?
tinfo_t ti;
std::vector<TypeInfo> typeChain;
if (frame->members[i].has_ti() && get_tinfo(&ti, frame->members[i].id)) {
//int typ = coreTypeLookup((int)ti.get_size(), getMetaTypeInfo(ti));
//msg("has struct member type info");
getType(ti, typeChain, false);
} else {
std::string metaType = "unknown";
int typ = DecompInterface::coreTypeLookup((int)get_member_size(&frame->members[i]), metaType);
if (typ == -1 && get_member_size(&frame->members[i]) != 1) {
typeChain.push_back(TypeInfo{ "", get_member_size(&frame->members[i]), "array", false, false, false, get_member_size(&frame->members[i]) });
typeChain.push_back(TypeInfo{ "undefined", 1, metaType });
} else {
typeChain.push_back(TypeInfo{ typ == -1 ? "undefined" : defaultCoreTypes[typ].name, get_member_size(&frame->members[i]), metaType });
}
coreTypeUsed[typ == -1 ? 1 : typ] = true;
}
func.syminfo.push_back(SymInfo{ {nm, typeChain}, {{"stack", frame->members[i].get_soff() - frame_off_retaddr(f)}, get_member_size(&frame->members[i])},
is_funcarg_off(f, frame->members[i].get_soff()) ? (int)curArgs++ : -1 }); //frame->members[i].get_soff() >= firstarg or f->frsize - f->frregs
}
} else {
unsigned long long retSize = 0;
if (f != nullptr && (f->is_far() || (f->flags & FUNC_USERFAR) != 0)) retSize += ph.segreg_size;
else if (f == nullptr && bFuncTinfo) {
tinfo_t ti;
func_type_data_t ftd;
getFuncByGuess((ea_t)addr.offset, ti);
ti.get_func_details(&ftd);
if (ftd.get_call_method() == FTI_FARCALL || ftd.get_call_method() == FTI_DEFCALL && is_code_far(inf_cc_cm)) retSize += ph.segreg_size;
}
//bitrange_t bits;
//const char* regnm = get_reg_info(ash.a_curip, &bits); //use default processor name
//reg_info_t ri;
//parse_reg_name(&ri, regnm == nullptr ? ash.a_curip : regnm);
//retSize += ri.size;
retSize += f == nullptr ? inf_is_64bit() ? 8 : (inf_is_32bit() ? 4 : 2) : get_func_bytes(f); //per documentation of get_func_bitness
//type arguments need stack adjustment but there is no frame?
for (size_t i = 0; i < func.syminfo.size(); i++) {
if (func.syminfo[i].addr.addr.space == "stack") {
func.syminfo[i].addr.addr.offset += retSize;
}
}
//only need to figure out return address size and adjust extraPop which depending on type info or not may affect the model
//it would be really nice to have context for which cref was used!
if (func.extraPop == -1) {
std::map<sval_t, int> histogram;
for (ea_t ea = get_first_cref_to((ea_t)addr.offset); ea != BADADDR;) {
//if points is nullptr, IDA wont retrieve and fill it unless get_spd or the like is called with non-null pointer func_t first
func_t* ft = get_func(ea); //IDA will not retrieve spd information except for function head as per decompiling ida64.dll where after it uses ea2node, netnode_qgetblob and then unpack_dq to retrieve it
//get_spd(f, f->start_ea); //passing null unlike API documentation will not yield useful results if not already populated
/*if (f != nullptr && f->points != nullptr) {
for (int i = 0; i < f->pntqty; i++) {
if (f->points[i].ea == get_item_end(ea)) {
sval_t s = f->points[i].spd - (i == 0 ? 0 : f->points[i - 1].spd);
}
}
}*/
histogram[get_spd(ft, get_item_end(ea)) - get_spd(ft, ea)]++;
ea = get_next_cref_to((ea_t)addr.offset, ea);
}
std::map<sval_t, int>::iterator max =
std::max_element(histogram.begin(), histogram.end(), [](std::pair<sval_t, int> p1, std::pair<sval_t, int> p2) { return p1.second < p2.second; });
if (max != histogram.end()) func.extraPop = max->first;
}
func.extraPop = func.extraPop == -1 ? retSize : func.extraPop + retSize;
/*for (ea_t ea = get_first_cref_to(f->start_ea); ea != BADADDR; ea = get_next_cref_to(f->start_ea, ea)) {
func_t* fp = get_func(ea);
if (fp != nullptr) {
get_spd(fp, fp->start_ea);
if (definedFuncs.find(fp->start_ea) == definedFuncs.end()) continue;
if (fp->points != nullptr) {
for (int i = 0; i < fp->pntqty; i++) { //can build a histogram and take the winner
if (fp->points[i].ea == get_item_end(ea)) {
//*extraPop = fp->points[i].spd - (i == 0 ? 0 : fp->points[i - 1].spd);
//if ((*extraPop & (1ull << 63)) != 0)* extraPop = 2; //make it cdecl
}
}
}
}
}*/
//if (bFuncTinfo) {//adjust arguments
//} else {
//}
//return address size based on model
//x86-64 bit far/interupt calling aligns everything like flags, error codes, stack pointer and stack register to 64 bits each
//if (ftd.get_call_method() == FTI_FARCALL || ftd.get_call_method() == FTI_DEFCALL && is_code_far(inf_cc_cm)) {
//if (f->is_far() || (f->flags & FUNC_USERFAR) != 0 || imports.find(offset) != imports.end()) {
//ph.max_ptr_size(); - for some reason is 48 bits on 64-bit systems?
//ph.get_stkarg_offset();
//ph.segreg_size
//syminfo[i].offset += ph.segreg_size + (inf_is_64bit() ? 8 : inf_is_32bit() == 1 ? 4 : 2);
//} else if (ftd.get_call_method() == FTI_NEARCALL || ftd.get_call_method() == FTI_DEFCALL && !is_code_far(inf_cc_cm)) {
//} else {
//syminfo[i].offset += (inf_is_64bit() ? 8 : inf_is_32bit() == 1 ? 4 : 2);
//} else if (ftd.get_call_method() == FTI_INTCALL) {
//syminfo[i].offset += ph.segreg_size + (inf_is_64bit() ? 8 : inf_is_32bit() == 1 ? 4 : 2); //far pointer to old stack, e/rflags, error code
//}
}
if (f != nullptr) {
/*for (int i = 0; i < ph.regs_num; i++) {
bitrange_t bits;
const char* regnm = nullptr;
regvar_t* rv = find_regvar(f, BADADDR, ph.reg_names[i]); //all general registers
regnm = get_reg_info(ph.reg_names[i], &bits); //use default processor name
if (regnm != nullptr && strcmp(regnm, ph.reg_names[i]) != 0) rv = find_regvar(f, BADADDR, regnm); //all general registers
if (rv != nullptr) {}
}*/
if (f->regvars == nullptr) find_regvar(f, f->start_ea, nullptr); //convience function to always load regvars since canon can be null and the load already occurred from the database
if (f->regvarqty != -1 && f->regvars != nullptr) {
for (int i = 0; i < f->regvarqty; i++) {
//f->regvars[i].cmt; //can be nullptr
reg_info_t ri;
parse_reg_name(&ri, f->regvars[i].canon); //does it need to be translated to default via get_reg_info?
std::vector<TypeInfo> typeChain;
std::string metaType = "unknown";
int typ = DecompInterface::coreTypeLookup((int)ri.size, metaType);
if (typ == -1 && ri.size != 1) {
typeChain.push_back(TypeInfo{ "", (unsigned long long)ri.size, "array", false, false, false, (unsigned long long)ri.size });
typeChain.push_back(TypeInfo{ "undefined", 1, metaType });
} else {
typeChain.push_back(TypeInfo{ typ == -1 ? "undefined" : defaultCoreTypes[typ].name, (unsigned long long)ri.size, metaType });
}
coreTypeUsed[typ == -1 ? 1 : typ] = true; //name base is p for pointer, a for array, other wise first char of type name
func.syminfo.push_back(SymInfo{ {f->regvars[i].user == nullptr || f->regvars[i].user[0] == 0 ? std::string(1, typ == -1 ? 'u' : defaultCoreTypes[typ].name[0]) + "Var_" + std::string(f->regvars[i].canon) : f->regvars[i].user,typeChain },
{{"register", (unsigned long long)regNameToIndexIda(f->regvars[i].canon)}, (unsigned long long)ri.size}, -1, RangeInfo{ addr.space, f->regvars[i].start_ea, f->regvars[i].end_ea } });
}
}
/*syminfo.erase(std::remove_if(syminfo.begin(), syminfo.end(), [](SymInfo it) { return it.name == ""; }), syminfo.end()); //or should give names - but often not used or necessary - dont mark in argument category at least
//need to remove argument indexes however if deleting arguments
curArgs = 0;
for (int i = 0; i < syminfo.size(); i++) {
if (syminfo[i].argIndex == -1) continue;
if (syminfo[i].argIndex == curArgs) curArgs++;
else syminfo[i].argIndex = curArgs++;
}*/
}
}
void IdaCallback::getMappedSymbol(AddrInfo addr, MappedSymbolInfo& msi)
{
executeOnMainThread([this, &msi, addr]() {
msi.kind = KIND_HOLE;
if (addr.space == "register") {} else if (addr.space == "ram") {
if (imports.find((ea_t)addr.offset) != imports.end()) {
usedImports[(ea_t)addr.offset] = true;
//Ghidra currently has 2 bugs one with restoring CS register if not simulating same segment fixups and the other calling back for external ref function info
//16-bit apps have functions defined for imports also...
if (isX86() && !inf_is_32bit() && !inf_is_64bit() && get_func((ea_t)addr.offset) != nullptr) msi.kind = KIND_FUNCTION;
else
msi.kind = KIND_EXTERNALREFERENCE;
} else {
if (get_func((ea_t)addr.offset) != nullptr) {
msi.kind = KIND_FUNCTION;
} else {
flags_t fl = get_flags((ea_t)addr.offset);
//if (is_func(fl)) msi.kind = KIND_FUNCTION; //function start only
//if (exists_fixup(offset)) msi.kind = KIND_EXTERNALREFERENCE; //fixups is not really a determining criterion in exported functions
if (is_data(fl) || is_unknown(fl) && is_mapped((ea_t)addr.offset)) msi.kind = KIND_DATA;
else if (has_name(fl) || has_dummy_name(fl)) msi.kind = KIND_LABEL; //dummy name/label for code only is_code(fl)...
//if (is_unknown(fl) && !is_mapped(offset))
}
}
} else if (addr.space == "stack") {}
if (msi.kind == KIND_HOLE) {
//flags_t f = get_flags(offset);
//no information about a segment should still assume writable
//volatile for unmapped memory should be based on the life of the system
//volatile for mapped memory should be based on the life of the program
//volatile for stack and registers should be based on the life of a function
//const and unique would not be volatile ever, though a join space could be comprised of members who are volatile
if (addr.space == "ram") {
//prev_addr(offset); prev_head(offset, inf_min_ea); prev_that(offset, inf_max_ea, [](flags_t f, void* ud) { return true; });
//next_addr(offset); next_head(offset, inf_max_ea); next_that(offset, inf_max_ea, [](flags_t f, void* ud) { return true; });
getMemoryInfo(addr.offset, &msi.readonly, &msi.volatil);
} else {//if (base == "register" || base == "stack") {
msi.readonly = false;
msi.volatil = addr.space != "register"; //far more conservative to assume not volatile until figure out how to determine this - perhaps pspec must explicitly define
}
} else if (msi.kind == KIND_LABEL) {
if (addr.space == "ram") {
getMemoryInfo(addr.offset, &msi.readonly, &msi.volatil);
msi.name = getSymbolName(addr.offset);
} else {
msi.readonly = false;
msi.volatil = addr.space != "register";
}
} else if (msi.kind == KIND_DATA) {
if (addr.space == "ram") {
msi.name = lookupDataInfo(addr.offset, &msi.readonly, &msi.volatil, msi.typeChain);
} else {
msi.readonly = false;
msi.volatil = addr.space != "register";
}
} else if (msi.kind == KIND_EXTERNALREFERENCE) {
if (addr.space == "ram") {
if (imports.find((ea_t)addr.offset) != imports.end() && imports[(ea_t)addr.offset].name != "") {
msi.name = demangle_name(imports[(ea_t)addr.offset].name.c_str(), MNG_SHORT_FORM).c_str();
if (msi.name.size() == 0) msi.name = imports[(ea_t)addr.offset].name;
}
if (msi.name.size() == 0) msi.name = get_short_name((ea_t)addr.offset, GN_STRICT).c_str();
if (msi.name.size() != 0) msi.name = msi.name.substr(0, msi.name.find("(", 0));
else msi.name = getSymbolName(addr.offset);
}
/*fixup_data_t fd;
get_fixup(&fd, offset);
qstring buf;
get_fixup_desc(&buf, offset, fd);
buf.c_str();*/
} else if (msi.kind == KIND_FUNCTION) {
//get_func_name(&name, f->start_ea);
func_t* f = get_func((ea_t)addr.offset);
msi.entryPoint = (f != nullptr) ? f->start_ea : addr.offset;
if (msi.entryPoint != addr.offset) {
if (f != nullptr) {
rangeset_t rangeset;
if (get_func_ranges(&rangeset, f) != BADADDR) {
for (rangeset_t::iterator it = rangeset.begin(); it != rangeset.end(); it++) {
msi.ranges.push_back(RangeInfo{ addr.space, it->start_ea, it->end_ea });
}
}
}
} else {
if (f != nullptr) {
if (addr.offset == f->start_ea && definedFuncs.find((ea_t)addr.offset) == definedFuncs.end() && imports.find((ea_t)addr.offset) == imports.end()) usedFuncs[(ea_t)addr.offset] = true;
//find_func_bounds(f, FIND_FUNC_NORMAL); //size minimally 1 or maximally must be contiguous block from entry point
//but func_t already contiguous and the tails account for the rest so end_ea and size are a valid way dont need to find this or first from func ranges should do
//*size = f->size();
rangeset_t rangeset;
msi.size = get_func_ranges(&rangeset, f) == BADADDR ? f->size() : rangeset.begin()->size();
} else msi.size = 1; //Ghidra uses 1 always despite its commentary
if (funcProtoInfos.find((ea_t)msi.entryPoint) != funcProtoInfos.end()) {
msi.name = funcProtoInfos[(ea_t)msi.entryPoint].name;
msi.func = funcProtoInfos[(ea_t)msi.entryPoint].fpi;
} else {
getFuncInfo(addr, f, msi.name, msi.func);
funcProtoInfos[(ea_t)msi.entryPoint] = FuncInfo{ msi.name.c_str(), false, msi.func };
}
}
}
});
}
void IdaCallback::getFuncTypeInfo(const tinfo_t & ti, bool paramOnly, FuncProtoInfo& func)
{
asize_t retSize = 0;
func_type_data_t ftd;
if (ti.is_func() && ti.get_func_details(&ftd)) { //GTD_NO_ARGLOCS
//(ftd.flags & FTI_SPOILED) != 0
for (size_t i = 0; i < ftd.spoiled.size(); i++) {
qstring qs;
get_reg_name(&qs, ftd.spoiled[i].reg, ftd.spoiled[i].size);
unsigned long long offset = regNameToIndexIda(qs.empty() ? ph.reg_names[ftd.spoiled[i].reg] : qs.c_str());
func.killedByCall.push_back(SizedAddrInfo{ {"register", offset}, (unsigned long long)ftd.spoiled[i].size });
}
func.dotdotdot = ftd.is_vararg_cc();
func.hasThis = (ftd.get_cc() & CM_CC_MASK) == CM_CC_THISCALL;
func.isNoReturn = (ftd.flags & FTI_NORET) != 0;
func.customStorage = is_user_cc(ftd.get_cc());
//switch (get_cc(inf_cc_cm)) {
//switch (get_cc(guess_func_cc(fd, ti.calc_purged_bytes(), CC_CDECL_OK | CC_ALLOW_ARGPERM | CC_ALLOW_REGHOLES | CC_HAS_ELLIPSIS))) {
func.model = ccToStr(ftd.cc, ftd.get_call_method());
for (size_t i = 0; i < ftd.size(); i++) {
unsigned long long offs;
//int typ = coreTypeLookup((int)ftd[i].type.get_size(), getMetaTypeInfo(ftd[i].type));
std::vector<SizedAddrInfo> joins;
std::string space = arglocToAddr(ftd[i].argloc, &offs, joins, paramOnly);
//argloc offset is relative to the frame and not properly adjusted for the stack
//need to at least adjust for return address size or problems will occur in 16-bit exports!
//if (qs.size() == 0) ftd[i].type.print(&qs, NULL, PRTYPE_1LINE);
//core types must be resolved here since the printing will not be queryable later such as for multi token values like "unsigned int"
//need to include a fixed core type typedef - it could be reduced only by scanning the file decompiled output
std::vector<TypeInfo> typeChain;
getType(ftd[i].type, typeChain, false);
qstring qs;
if (ftd[i].name.size() == 0 && space == "register") get_reg_name(&qs, ftd[i].argloc.reg1(), ftd[i].type.get_size());
func.syminfo.push_back(SymInfo{ {ftd[i].name.size() == 0 && space == "register" ? "in_" + std::string(qs.c_str()) : ftd[i].name.c_str(), typeChain },
{{space, offs, joins}, ftd[i].type.get_size()}, (int)i, {} });
}
func.retType.addr.addr.space = arglocToAddr(ftd.retloc, &func.retType.addr.addr.offset, func.retType.addr.addr.joins, paramOnly);
func.retType.addr.size = ftd.rettype.get_size();
if (func.retType.addr.size == BADSIZE) func.retType.addr.size = 0; //0 is void
//qstring qs;
//ftd.rettype.get_type_name(&qs);
getType(ftd.rettype, func.retType.pi.ti, false);
func.extraPop = ti.calc_purged_bytes();
//ti.is_vararg_cc();
//local variables still need to be processed
} else {
func.extraPop = -1; //need size of return address which is also popped
argloc_t al;
const tinfo_t t(inf_is_64bit() ? BT_INT64 : (inf_is_32bit() ? BT_INT32 : BT_INT16)); //or use BT_INT8 - 1 byte like Ghidra?
#ifdef __X64__
if (ph.calc_retloc(&al, t, inf_cc_cm) == 1)
#else
if (ph.notify(ph.calc_retloc3, &t, inf_cc_cm, &al) == 2)
#endif
func.retType.addr.addr.space = arglocToAddr(al, &func.retType.addr.addr.offset, func.retType.addr.addr.joins, false);
else {
func.retType.addr.addr.space = "register"; // "ram";
qstring qs;
get_reg_name(&qs, 0, t.get_size());
func.retType.addr.addr.offset = regNameToIndexIda(qs.empty() ? ph.reg_names[0] : qs.c_str());
func.retType.addr.size = t.get_size();
}
std::string metaType = "unknown"; //still unknown really
int typ = DecompInterface::coreTypeLookup((size_t)func.retType.addr.size, metaType);
func.retType.pi.ti.push_back(TypeInfo{ typ == -1 ? "undefined" : defaultCoreTypes[typ].name.c_str(), func.retType.addr.size, metaType });
coreTypeUsed[typ == -1 ? 1 : typ] = true;
func.model = "unknown";
}
}
bool IdaCallback::getFuncTypeInfoByAddr(ea_t ea, FuncProtoInfo& func)
{
tinfo_t ti;
bool bFuncTinfo = getFuncByGuess(ea, ti);
getFuncTypeInfo(ti, false, func);
return bFuncTinfo;
}
bool IdaCallback::checkPointer(unsigned long long offset, std::vector<TypeInfo>& typeChain, std::vector<ea_t> & deps)
{
//ea_t ea = offset;
//deref_ptr2(get_idati(), &ea, nullptr);
tinfo_t ti;
if (exists_fixup((ea_t)offset)) {//need to detect pointers
fixup_data_t fd;
get_fixup(&fd, (ea_t)offset);
//uval_t u = get_fixup_value(offset, fd.get_type()); //terminate circular types with pointer chain situation
#ifdef __X64__
//if (!fd.is_extdef()) return false;
uval_t u = fd.get_base(); //get_fixup_extdef_ea
#else
//if ((fd.type & FIXUP_EXTDEF) != 0) return false;
uval_t u = get_fixup_base((ea_t)offset, &fd); // (fd.type & FIXUP_REL) != 0 ? 0 : (fd.sel != BADSEL ? sel2ea(fd.sel) : 0); //get_fixup_extdef_ea
#endif
u += fd.off;
if (is_mapped(u) && has_any_name(get_flags(u))) deps.push_back(u);
if (usedData.find(u) != usedData.end()) return false;
typeChain.push_back(TypeInfo{ "", (unsigned long long)calc_fixup_size(fd.get_type()), "ptr", false, false, false });
if (is_mapped(u) && has_any_name(get_flags(u))) {
std::vector<TypeInfo> nextType;
if (is_func(get_flags(u))) {
usedFuncs[u] = true;
bool bFuncTinfo = getFuncByGuess(u, ti);
getType(ti, nextType, false);
if (funcProtoInfos.find(u) == funcProtoInfos.end()) {
FuncProtoInfo innerFunc;
getFuncTypeInfo(ti, false, innerFunc);
qstring name;
//get_func_name(&name, f->start_ea);
name = get_short_name((ea_t)offset, GN_STRICT);
if (name.size() != 0) name = name.substr(0, name.find("(", 0));
else name = getSymbolName(offset).c_str();
funcProtoInfos[u] = FuncInfo{ name.c_str(), false, innerFunc };
}
} else {
bool rdonly, volat;
lookupDataInfo(u, &rdonly, &volat, nextType);
}
typeChain.insert(typeChain.end(), nextType.begin(), nextType.end());
} else {
typeChain.push_back(TypeInfo{ "void", 0, "void" });
}
return true;
} else {
unsigned long long size = get_item_size((ea_t)offset);
//if (is_unknown(offset)) size = next_head(offset, BADADDR) - offset;
bool foundPtr = false;
if ((inf_cc_cm & CM_MASK) == CM_N32_F48 && size == 4) {
uval_t u;
if (!get_data_value(&u, (ea_t)offset, (asize_t)size)) return false;
if (is_mapped(u) && has_any_name(get_flags(u))) deps.push_back(u);
if (usedData.find(u) != usedData.end()) return false;
if (is_mapped(u) && has_any_name(get_flags(u))) {
typeChain.push_back(TypeInfo{ "", size, "ptr", false, false, false });
std::vector<TypeInfo> nextType;
if (is_func(get_flags(u))) {
usedFuncs[u] = true;
bool bFuncTinfo = getFuncByGuess(u, ti);
getType(ti, nextType, false);
if (funcProtoInfos.find(u) == funcProtoInfos.end()) {
FuncProtoInfo innerFunc;
getFuncTypeInfo(ti, false, innerFunc);
qstring name;
//get_func_name(&name, f->start_ea);
name = get_short_name((ea_t)offset, GN_STRICT);
if (name.size() != 0) name = name.substr(0, name.find("(", 0));
else name = getSymbolName(offset).c_str();
funcProtoInfos[u] = FuncInfo{ name.c_str(), false, innerFunc };
}
} else {
bool rdonly, volat;
lookupDataInfo(u, &rdonly, &volat, nextType);
}
typeChain.insert(typeChain.end(), nextType.begin(), nextType.end());
return true;
}
}
}
return false;
}
void IdaCallback::consumeTypeInfo(int idx, std::vector<TypeInfo>& tc, unsigned long long ea, std::vector<ea_t> & deps)
{
if (tc[idx].size == -1) {
std::vector<TypeInfo> nextChain;
tinfo_t ti;
ti.get_named_type(get_idati(), tc[idx].typeName.c_str());
qstring qs;
ti.get_final_type_name(&qs);
getType(ti, nextChain);
size_t sz = nextChain.size();
consumeTypeInfo(0, nextChain, ea, deps); //but if addition occurs from is_strlit... then its lost
if (nextChain.size() != sz) tc.insert(tc.begin(), *nextChain.begin());
} else if (tc[idx].metaType == "ptr") {
std::vector<TypeInfo> nextChain;
checkPointer(ea, nextChain, deps); //end recursion since pointer is only recursed through new data type if not already traced
} else if (tc[idx].metaType == "array") { //unions and bitfields consumed in this way
unsigned long long elSize = tc[idx + 1].size;
if (elSize == -1) {
tinfo_t ti;
if (ti.get_named_type(get_idati(), tc[idx + 1].typeName.c_str())) {
elSize = ti.get_size();
}
}
if (tc[idx].size == 0) { //0 length array can only be alone or very last member of structure which recursively chains up to a top structure
tc[idx].size = get_item_size((ea_t)ea);
tc[idx].arraySize = tc[idx].size / elSize;
} else {
//could be an array of structures, arrays, or pointers
if (!is_strlit(get_flags((ea_t)ea)) || (elSize != sizeof(char) && elSize != sizeof(wchar16_t) && elSize != sizeof(wchar32_t))) { //must prevent auto detection here
for (int i = 0; i < tc[idx].arraySize; i++) {
consumeTypeInfo(idx + 1, tc, ea + elSize * i, deps);
}
}
}
} else if (tc[idx].metaType == "struct") {
for (size_t i = 0; i < tc[idx].structMembers.size(); i++) {
consumeTypeInfo(0, tc[idx].structMembers[i].ti, ea + tc[idx].structMembers[i].offset, deps);
}
} else if (is_strlit(get_flags((ea_t)ea)) && tc[idx].metaType != "array" && (tc[idx].size == sizeof(char) || tc[idx].size == sizeof(wchar16_t) || tc[idx].size == sizeof(wchar32_t)) &&
get_item_size((ea_t)ea) % tc[idx].size == 0) {
//probably need more heuristics than just to verify the type is char, wchar_t or wchar16/32
tc.insert(tc.begin() + idx, TypeInfo{ "", get_item_size((ea_t)ea), "array", false, false, false, get_item_size((ea_t)ea) / tc[idx].size });
//msg("wrong string is not array\n");
}
}
std::string IdaCallback::lookupDataInfo(unsigned long long offset, bool* readonly, bool* volatil, std::vector<TypeInfo>& typeChain)
{
unsigned long long size = (is_unknown(get_flags((ea_t)offset))) ? calc_max_item_end((ea_t)offset) - offset : get_item_size((ea_t)offset);
tinfo_t ti;
std::vector<ea_t> deps;
//is_strlit(get_flags(offset))
if (!is_unknown(get_flags((ea_t)offset)) && get_tinfo(&ti, (ea_t)offset)) {
getType(ti, typeChain, false);
//recursive pointer scan and also 0 length array fix, string identification fix
consumeTypeInfo(0, typeChain, offset, deps);
//0 length arrays cause a problem but only one should occur but could be at the end of a structure
/*if (typeChain.begin()->metaType == "array" && typeChain.begin()->size == 0) {
typeChain.begin()->size = size;
unsigned long long elSize = (typeChain.begin() + 1)->size;
if (elSize == -1) {
tinfo_t ti;
if (ti.get_named_type(get_idati(), (typeChain.begin() + 1)->typeName.c_str())) {
elSize = ti.get_size();
}
}
typeChain.begin()->arraySize = size / elSize;
}*/
} else if (!checkPointer(offset, typeChain, deps)) { //need to detect pointers
std::string metaType = "unknown";
int typ = DecompInterface::coreTypeLookup((size_t)size, metaType);
if (typ == -1 && size != 1) {
typeChain.push_back(TypeInfo{ "", size, "array", false, false, false, size });
typeChain.push_back(TypeInfo{ "undefined", 1, metaType });
} else {
typeChain.push_back(TypeInfo{ typ == -1 ? "undefined" : defaultCoreTypes[typ].name, size, metaType });
}
coreTypeUsed[typ == -1 ? 1 : typ] = true;
}
//*size = ti.get_size();
//qstring qs;
//print_type(&qs, offset, PRTYPE_MULTI);
//msg((qs + "\n").c_str());
typeChain.begin()->isReadOnly = readonly;
usedData[(ea_t)offset] = typeChain;
dependentData[(ea_t)offset] = deps;
getMemoryInfo(offset, readonly, volatil);
return getSymbolName(offset);
}
void IdaCallback::getExternInfo(AddrInfo addr, std::string& callName, std::string& modName, FuncProtoInfo& func)
{
if (addr.space != "ram") return;