-
Notifications
You must be signed in to change notification settings - Fork 29
/
sleighinterface.cpp
3361 lines (3244 loc) · 140 KB
/
sleighinterface.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
//Java has its own entire Sleigh library implementation used by Ghidra UI app:
//Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/lang
//In C the equivalent is building a custom one starting with:
//Ghidra/Features/Decompiler/src/decompile/cpp/sleighexample.cc
//Requires source:
//SLEIGH=sleigh pcodeparse pcodecompile sleighbase slghsymbol
// slghpatexpress slghpattern semantics context filemanage
//CORE= xml space float address pcoderaw translate opcodes globalcontext
//LIBSLA_NAMES=$(CORE) $(SLEIGH) loadimage sleigh memstate emulate opbehavior
//also types.h error.hh partmap.hh
//address.cc conflicts with address.cpp of retdec so rename it to address_.cpp
//pcodeparse.y and xml.y require: https://sourceforge.net/projects/winflexbison/
//Project->Build Dependencies->Build Customizations... Find Targets win_flex_bison\custom_build_rules\win_flex_bison_custom_build.targets
//copy win_bison.exe and data folder to Project folder and add *.y files as top level items
//pcodeparsetab.cpp and xml.tab.cpp conflict requires -p zz bison option to change yy to zz in one of them for:
//functions yylex, yyerror, yyparse, and variables yychar, yylval, yynerrs
//
//sleigh.exe meanwhile merely compiles raw specification files .slaspec into .sla compiled specification files
// it appears to be unused in the Ghidra UI app
//JVM/Dalvik - C Pool Ref and 3 Pcode injection calls dynamic implementation needs to be ripped from Java code
//Building decompiler: need GNU BFD (binary file descriptor library) - https://sourceware.org/binutils/
#define _CRT_SECURE_NO_WARNINGS
// Dump the raw pcode instructions
// Root include for parsing using SLEIGH
#include "loadimage.hh"
#include "sleigh.hh"
#include "emulate.hh"
#include "pcodeparse.hh"
#include "filemanage.hh"
//g++ -std=c++1y -m64 -I include -I . -D__IDP__ -D__PLUGIN__ -DNO_OBSOLETE_FUNCS -D__X64__ -D__LINUX__ -fpermissive sleighinterface.cpp
#include <iostream>
#include <memory>
#include <thread>
#include <future>
#include <stack>
#include "sleighinterface.h"
//typeop.cc
//ZEXT#(I)_#(O) - cast to unsigned #(O) size
//SEXT#(I)_#(O) - cast to signed #(O) size
//#define CONCAT(SZI1, SZI2, VAL1, VAL2) (((VAL1) << (SZI2 * 8)) | (VAL2))
//CONCAT#(I1)_#(I2) - shift left/or idiom
//#define SUB(SZI, SZO, VAL) (((VAL) >> (SZ1 * 8)) & ((~0ull) >> (64 - SZO * 8)))
//SUB#(I)_#(O) - shift right/and idiom, careful that 64 bits does not get truncated
//#define CARRY(SZ, VAL1, VAL2) (((((1ull << (SZ * 8 - 1)) & (VAL1)) != 0) && (((1ull << (SZ * 8 - 1)) & (VAL2)) != 0)) || (((1ull << (SZ * 8 - 1)) & (VAL1)) ^ ((1ull << (SZ * 8 - 1)) & (VAL2))) != 0 && (((VAL1) + (VAL2)) & (1ull << (SZ * 8 - 1))) == 0)
//CARRY#(I) - addition comparison idiom - both high bits are set or one high bit is set and their addition causes the high bit to clear 0 1 0/1 0 0/1 1 _
//#define SCARRY(SZ, VAL1, VAL2) (((1ull << (SZ * 8 - 1)) & (VAL1)) == ((1ull << (SZ * 8 - 1)) & (VAL2)) && (((VAL1) + (VAL2)) & (1ull << (SZ * 8 - 1))) != ((1ull << (SZ * 8 - 1)) & (VAL1)))
//SCARRY#(I) - signed addition comparison idiom - both are positive or both are negative and their addition causes the high bit to be opposite of inputs 0 0 1/1 1 0
//#define SBORROW(SZ, VAL1, VAL2) (((1ull << (SZ * 8 - 1)) & (VAL1)) != ((1ull << (SZ * 8 - 1)) & (VAL2)) && (((VAL1) - (VAL2)) & (1ull << (SZ * 8 - 1))) != ((1ull << (SZ * 8 - 1)) & (VAL1)))
//SBORROW#(I) - signed subtraction comparison idiom - one is negative and one is positive and their subtraction causes the high bit to be opposite first input/same as second input 0 1 1/1 0 0
//NAN - needs math.h along with ABS, SQRT, CEIL, FLOOR, ROUND
//ABS - fabs, fabsf, fabsl
//SQRT - sqrtf, sqrt, sqrtl
//CEIL - ceil, ceilf, ceill
//FLOOR - floor, floorf, floorl
//ROUND - round, roundf, roundl
const char* szExtensionMacros[] = { "ZEXT", "SEXT", //2 numeric values for input size, output size
"CARRY", "SCARRY", "SBORROW", //1 numeric value for input size
"NAN", "ABS", "SQRT",
/*"INT2FLOAT", "FLOAT2FLOAT", "TRUNC",*/ //handled with type casts in printc.cc
"CEIL", "FLOOR", "ROUND",
"CONCAT", //2 numeric values for 1st input size, 2nd input size
"SUB" //2 numeric values for input size, output size
};
const Options defaultOptions = { true, true, true, true, false, true, false, false, true, false,
100, 2, 20, std::string("c"), false, true, false, false, true, true, true,
std::string("best"), std::string("c-language") };
const DecMode defaultDecMode = { std::string("decompile"), true, true, false, false };
// Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/data/ *DataType.java
// Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/pcode/PcodeDataTypeManager.java
// Ghidra/Features/Decompiler/src/decompile/cpp/ghidra_arch.cc setCoreType - specifies default if none are sent
//type.cc Datatype::hashName produces the IDs - first name of aliases will be the preferred one currently
CoreType defaultCoreTypes[] = {
{ std::string("void"), 0, std::string("void") }, //ghidra_arch.cc
{ std::string("undefined"), 1, std::string("unknown") }, //ghidra_arch.cc
{ std::string("undefined1"), 1, std::string("unknown") },
{ std::string("undefined2"), 2, std::string("unknown") }, //ghidra_arch.cc
{ std::string("undefined3"), 3, std::string("unknown") },
{ std::string("undefined4"), 4, std::string("unknown") }, //ghidra_arch.cc
{ std::string("undefined5"), 5, std::string("unknown") },
{ std::string("undefined6"), 6, std::string("unknown") },
{ std::string("undefined7"), 7, std::string("unknown") },
{ std::string("undefined8"), 8, std::string("unknown") }, //ghidra_arch.cc
{ std::string("sbyte"), 1, std::string("int") }, //ghidra_arch.cc
{ std::string("short"), 2, std::string("int") },
{ std::string("sword"), 2, std::string("int") }, //ghidra_arch.cc
{ std::string("int3"), 3, std::string("int") },
{ std::string("int"), 4, std::string("int") },
{ std::string("sdword"), 4, std::string("int") }, //ghidra_arch.cc
{ std::string("int5"), 5, std::string("int") },
{ std::string("int6"), 6, std::string("int") },
{ std::string("int7"), 7, std::string("int") },
{ std::string("long"), 8, std::string("int") },
{ std::string("sqword"), 8, std::string("int") }, //ghidra_arch.cc
{ std::string("longlong"), 8, std::string("int") }, //alias
{ std::string("int16"), 16, std::string("int") },
{ std::string("byte"), 1, std::string("uint") }, //ghidra_arch.cc
{ std::string("ushort"), 2, std::string("uint") },
{ std::string("word"), 2, std::string("uint") }, //ghidra_arch.cc
{ std::string("uint3"), 3, std::string("uint") },
{ std::string("uint"), 4, std::string("uint") },
{ std::string("dword"), 4, std::string("uint") }, //ghidra_arch.cc
{ std::string("uint5"), 5, std::string("uint") },
{ std::string("uint6"), 6, std::string("uint") },
{ std::string("uint7"), 7, std::string("uint") },
{ std::string("ulong"), 8, std::string("uint") },
{ std::string("qword"), 8, std::string("uint") }, //ghidra_arch.cc
{ std::string("ulonglong"), 8, std::string("uint") }, //alias
{ std::string("uint16"), 16, std::string("uint") },
{ std::string("float2"), 2, std::string("float") },
{ std::string("float"), 4, std::string("float") }, //ghidra_arch.cc
{ std::string("double"), 8, std::string("float") },
{ std::string("float8"), 8, std::string("float") }, //ghidra_arch.cc
{ std::string("float10"), 10, std::string("float") },
{ std::string("float16"), 16, std::string("float") }, //ghidra_arch.cc
{ std::string("longdouble"), 16, std::string("float") }, //alias
{ std::string("code"), 1, std::string("code") }, //ghidra_arch.cc
{ std::string("char"), sizeof(char), std::string("int"), sizeof(char) == 1, sizeof(char) == 2 }, //metatype=int/uint, size=1 for char/2 for utf //ghidra_arch.cc
{ std::string("wchar_t"), sizeof(wchar_t), std::string("int"), false, true }, //size=2/4
{ std::string("wchar16"), 2, std::string("int"), false, true },
{ std::string("wchar32"), 4, std::string("int"), false, true },
{ std::string("bool"), 1, std::string("bool") } //ghidra_arch.cc
};
const int numDefCoreTypes = sizeof(defaultCoreTypes) / sizeof(defaultCoreTypes[0]);
const char* szCoreTypeDefs[] = {
nullptr, "__int8", "__int8", "__int16", "__int32",
"__int32", "__int64", "__int64", "__int64", "__int64",
"__int8", nullptr, "__int16", "__int32", nullptr, "__int32", "__int64", "__int64",
"__int64", nullptr, "__int64", "__int64", "__int64",
"unsigned __int8", "unsigned __int16" , "unsigned __int16", "unsigned __int32",
"unsigned __int32", "unsigned __int32", "unsigned __int64", "unsigned __int64",
"unsigned __int64", "unsigned __int64", "unsigned __int64", "unsigned __int64",
"unsigned __int64",
"float", nullptr, nullptr, "double", "long double", "long double", "long double",
"void*", nullptr, nullptr, "char16_t", "char32_t", nullptr
};
const char* cpoolreftags[] = { "primitive", "string", "classref", "method",
"field", "arraylength", "instanceof", "checkcast" };
/// If a type id is explicitly provided for a data-type, this routine is used
/// to produce an id based on a hash of the name. IDs produced this way will
/// have their sign-bit set to distinguish it from other IDs.
/// \param nm is the type name to be hashed
uint8 hashName(const std::string& nm)
{
uint8 res = 123;
for (uint4 i = 0; i < nm.size(); ++i) {
res = (res << 8) | (res >> 56);
res += (uint8)nm[i];
if ((res & 1) == 0)
res ^= 0xfeabfeab; // Some kind of feedback
}
uint8 tmp = 1;
tmp <<= 63;
res |= tmp; // Make sure the hash is negative (to distinguish it from database id's)
return res;
}
template <class T>
string to_string(T t, ios_base& (__cdecl* f)(ios_base&))
{
ostringstream oss;
oss << f << t;
return oss.str();
}
std::string escapeCStr(std::string input)
{
std::string str;
for (int i = 0; i < input.size(); i++) {
if (isprint(input[i])) {
if (input[i] == '\\') str += "\\\\";
else if (input[i] == '"') str += "\\\"";
else str += input[i];
} else {
if (isspace(input[i])) str += input[i];
//if (input[i] == '\n') str += "\\n";
//else if (input[i] == '\r') str += "\\r";
else if (input[i] == '\a') str += "\\a";
else if (input[i] == '\b') str += "\\b";
//else if (input[i] == '\f') str += "\\f";
//else if (input[i] == '\t') str += "\\t";
//else if (input[i] == '\v') str += "\\v";
else {
std::string s = to_string((unsigned int)input[i], std::hex);
str += "0x" + std::string(2 - s.size(), '0') + s;
}
}
}
return str;
}
// This is a tiny LoadImage class which feeds the executable bytes to the translator
class CallbackLoadImage : public LoadImage {
DecompileCallback* callback;
public:
CallbackLoadImage(DecompileCallback* cb) : LoadImage("nofile"), callback(cb) { }
virtual void loadFill(uint1* ptr, int4 size, const Address& addr);
virtual string getArchType(void) const { return "unknown"; } //unused
virtual void adjustVma(long adjust) { } //unused
};
// This is the only important method for the LoadImage. It returns bytes from the static array
// depending on the address range requested
void CallbackLoadImage::loadFill(uint1* ptr, int4 size, const Address& addr)
{
if (callback->getBytes(ptr, size,
AddrInfo{ addr.getSpace()->getName(), addr.getOffset() }) == 0)
throw DecompError("No bytes could be loaded");
}
// -------------------------------
//
// These are the classes/routines relevant to printing a pcode translation
// Here is a simple class for emitting pcode. We simply dump an appropriate string representation
// straight to standard out.
class PackedPcodeRawOut : public PcodeEmit {
public:
virtual void dump(const Address& addr, OpCode opc,
VarnodeData* outvar, VarnodeData* vars, int4 isize);
std::string packedPcodes;
std::string xmlPcodes;
};
/*uchar unimpl_tag = 0x20, inst_tag = 0x21, op_tag = 0x22, void_tag = 0x23,
spaceid_tag = 0x24, addrsz_tag = 0x25, end_tag = 0x60;*/
std::string dumpOffset(unsigned long long val) {
std::string packed;
while (val != 0) {
uchar chunk = (int)(val & 0x3f);
val >>= 6;
packed += (chunk + 0x20);
}
packed += PcodeEmit::end_tag;
return packed;
}
std::string dumpVarnodeData(VarnodeData* v) {
std::string packed;
packed += PcodeEmit::addrsz_tag;
int spcindex = v->space->getIndex();
packed += (spcindex + 0x20);
packed += dumpOffset(v->offset);
packed += (v->size + 0x20);
return packed;
}
//const int ID_UNIQUE_SHIFT = 7;
std::string dumpSpaceId(VarnodeData* v) {
std::string packed;
packed += PcodeEmit::spaceid_tag;
//int spcindex = ((int)v->offset >> ID_UNIQUE_SHIFT);
//v->getAddr()->getSpaceFromConst()->getIndex();
int spcindex = ((AddrSpace*)v->offset)->getIndex();
packed += (spcindex + 0x20);
return packed;
}
/*struct LabelRef
{
int opIndex; // Index of operation referencing the label
int labelIndex; // Index of label being referenced
int labelSize; // Number of bytes in the label
int streampos; // Position in byte stream where label is getting encoded
};*/
//std::vector<LabelRef> labelrefs;
//int numOps = 0;
//int labelBase = 0;
//int labelCount = 0;
//std::vector<int> labeldefs;
void PackedPcodeRawOut::dump(const Address& addr, OpCode opc,
VarnodeData* outvar, VarnodeData* vars, int4 isize)
{
//int oldbase = labelBase;
//labelBase = labelCount;
//labelCount += construct.getNumLabels();
//PcodeCacher/PcodeBuilder seems to be already resolving all of this in C - so these issues probably never occur
/*if (opc == CPUI_MULTIEQUAL) { throw DecompError("CPUI_MULTIEQUAL"); }
else if (opc == CPUI_INDIRECT) { throw DecompError("CPUI_INDIRECT"); }
else if (opc == CPUI_PTRADD) {
throw DecompError("CPUI_PTRADD");
int labelindex = (int)vars[0].offset + labelBase;
while (labeldefs.size() <= labelindex) {
labeldefs.push_back(-1);
}
labeldefs[labelindex] = numOps;
}
else if (opc == CPUI_PTRSUB) { throw DecompError("CPUI_PTRSUB"); }*/
// Some spaces are "virtual", like the stack spaces, where addresses are really relative to a
// base pointer stored in a register, like the stackpointer. This routine will return non-zero
// if \b this space is virtual and there is 1 (or more) associated pointer registers
if ((isize > 0) && (vars[0].space->numSpacebase() != 0)) {
//int labelIndex = (int)vars[0].offset + labelBase;
//int labelSize = vars[0].size;
//labelrefs.push_back(LabelRef{ numOps, labelIndex, labelSize, (int)packedPcodes.size() });
// Force the emitter to write out a maximum length encoding (12 bytes) of a long
// so that we have space to insert whatever value we need to when this relative is resolved
vars[0].offset = -1;
}
//numOps++;
//labelBase = oldbase;
std::string packed;
packed += PcodeEmit::op_tag;
packed += (opc + 0x20);
if (outvar != (VarnodeData*)0) {
packed += dumpVarnodeData(outvar);
} else
packed += PcodeEmit::void_tag;
int4 i = 0;
if (opc == CPUI_LOAD || opc == CPUI_STORE) {
packed += dumpSpaceId(&vars[0]);
i = 1;
}
// Possibly check for a code reference or a space reference
for (; i < isize; ++i) {
packed += dumpVarnodeData(&vars[i]);
}
packed += PcodeEmit::end_tag;
packedPcodes += packed;
std::string inpstr;
for (int i = opc == CPUI_LOAD || opc == CPUI_STORE ? 1 : 0; i < isize; i++) {
inpstr += " <addr space=\"" + vars[i].space->getName() + "\" offset=\"0x" +
to_string(vars[i].offset, hex) +
"\" size=\"" + std::to_string(vars[i].size) + "\"/>\n";
}
xmlPcodes += " <op code=\"" + std::to_string(opc) + "\">\n" +
(outvar != nullptr ? " <addr space=\"" + outvar->space->getName() + "\" offset=\"0x" +
to_string(outvar->offset, hex) +
"\" size=\"" + std::to_string(outvar->size) + "\"/>\n" : " <void/>\n") +
(opc == CPUI_LOAD || opc == CPUI_STORE ?
" <spaceid name=\"" + vars[0].space->getName() + "\"/>\n" : "") +
inpstr + " </op>\n";
}
//PcodeCacher/PcodeBuilder is already resolving all of this on C side
/*void insertOffset(int streampos, long val, std::string& buf) {
while (val != 0) {
if (buf[streampos] == PcodeEmit::end_tag) {
throw DecompError("Could not properly insert relative jump offset");
}
int chunk = (int)(val & 0x3f);
val >>= 6;
buf[streampos] = chunk + 0x20;
streampos += 1;
}
for (int i = 0; i < 11; ++i) {
if (buf[streampos] == PcodeEmit::end_tag) {
return;
}
buf[streampos] = 0x20; // Zero fill
streampos += 1;
}
throw DecompError("Could not find terminator while inserting relative jump offset");
}
void resolveRelatives(std::string& buf) {
for (int i = 0; i < labelrefs.size(); i++) {
LabelRef ref = labelrefs[i];
if ((ref.labelIndex >= labeldefs.size()) || (labeldefs[ref.labelIndex] == -1)) {
throw DecompError("Reference to non-existent sleigh label");
}
long res = (long)labeldefs[ref.labelIndex] - (long)ref.opIndex;
if (ref.labelSize < 8) {
long mask = -1;
mask >>= (8 - ref.labelSize) * 8;
res &= mask;
}
// We need to skip over op_tag, op_code, void_tag, addrsz_tag, and spc bytes
insertOffset(ref.streampos + 5, res, buf); // Insert the final offset into the stream
}
}*/
//Ghidra/Features/Decompiler/src/decompile/cpp/translate.cc
//Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/app/plugin/processors/sleigh/SleighInstructionPrototype.java
//Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/app/plugin/processors/sleigh/PcodeEmit.java
//Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/app/plugin/processors/sleigh/PcodeEmitPacked.java
static std::pair<std::string, std::string> getPackedPcode(Translate& trans, AddrInfo addr)
{ // Dump pcode translation of machine instructions
PackedPcodeRawOut emit; // Set up the pcode dumper
int4 length; // Number of bytes of each machine instruction
//numOps = 0;
//labelBase = 0;
//labelCount = 0;
//labelrefs.clear();
//labeldefs.clear();
Address address(trans.getSpaceByName(addr.space), addr.offset); // First address to translate
std::string packed;
packed += PcodeEmit::inst_tag;
length = trans.oneInstruction(emit, address); // Translate instruction
packed += dumpOffset(length);
uchar spcindex = address.getSpace()->getIndex();
packed += (spcindex + 0x20);
packed += dumpOffset(address.getOffset());
//resolveRelatives(emit.packedPcodes);
packed += emit.packedPcodes;
packed += PcodeEmit::end_tag;
std::string xml = "<inst" " offset=\"" +
std::to_string(addr.offset) + "\">\n" + emit.xmlPcodes + "</inst>\n";
return std::pair<std::string, std::string>(packed, xml);
//if a failure occurs:
//packed += unimpl_tag;
//packed += dumpOffset(length);
}
//Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/app/plugin/processors/sleigh/PcodeEmitObjects.java
//Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/pcode/PcodeOp.java
class XmlPcodeEmit : public PcodeEmit {
public:
//PcodeCacher/PcodeBuilder already resolve
//void resolveRelatives() {
//for (int i = 0; i < labelref.size(); i++) {
/*int opindex = labelref.get(i);
PcodeOp op = oplist.get(opindex);
Varnode vn = op.getInput(0);
int labelid = (int)vn.getOffset();
if ((labelid >= labeldef.size()) || (labeldef.get(labelid) == null)) {
throw DecompError("Reference to non-existant sleigh label");
}
long res = (long)labeldef.get(labelid) - (long)opindex;
if (vn.getSize() < 8) {
long mask = -1;
mask >>>= (8 - vn.getSize()) * 8;
res &= mask;
}
AddressSpace spc = vn.getAddress().getAddressSpace();
vn = new Varnode(spc.getAddress(res), vn.getSize());
op.setInput(vn, 0);*/
//}
//}
//void addLabelRef() { labelref.push_back(numOps); }
virtual void dump(const Address& addr, OpCode opc,
VarnodeData* outvar, VarnodeData* vars, int4 isize)
{
std::string inpstr;
for (int i = opc == CPUI_LOAD || opc == CPUI_STORE ? 1 : 0; i < isize; i++) {
inpstr += " <addr space=\"" + vars[i].space->getName() + "\" offset=\"0x" +
to_string(vars[i].offset, hex) +
"\" size=\"" + std::to_string(vars[i].size) + "\"/>\n";
}
strs.push_back({ " <op code=\"" + std::to_string(opc) + "\">\n",
(outvar != nullptr ? " <addr space=\"" + outvar->space->getName() + "\" offset=\"0x" +
to_string(outvar->offset, hex) +
"\" size=\"" + std::to_string(outvar->size) + "\"/>\n" : " <void/>\n") +
(opc == CPUI_LOAD || opc == CPUI_STORE ?
" <spaceid name=\"" + vars[0].space->getName() + "\"/>\n" : "") +
inpstr + " </op>\n" });
}
std::string build(std::string space, uintb addr)
{
std::string str;
for (int i = 0; i < strs.size(); i++) {
str += strs[i].pre + " <seqnum space=\"" + space + "\" offset=\"0x" + to_string(addr, hex) +
"\" uniq=\"0x" + to_string(i, hex) + "\"/>\n" + strs[i].post;
}
return str;
}
//std::string xmlPcodes; //XML serialized vector of PcodeOpRaw
struct StrGroup { std::string pre; std::string post; };
std::vector<StrGroup> strs;
intb paramShift = 0; //only for callfixup
std::vector<std::pair<std::string, int>> inputs; //only for dynamic - callotherfixup, executablepcode
std::vector<std::pair<std::string, int>> outputs; //only for dynamic - callotherfixup, executablepcode
//std::vector<int> labelref;
};
//Interacting with decompile/decompile.exe:
//ghidra\app\decompiler\DecompileProcess.java
static const unsigned char command_start[] = { 0, 0, 1, 2 };
static const unsigned char command_end[] = { 0, 0, 1, 3 };
static const unsigned char query_response_start[] = { 0, 0, 1, 8 };
static const unsigned char query_response_end[] = { 0, 0, 1, 9 };
static const unsigned char string_start[] = { 0, 0, 1, 14 };
static const unsigned char string_end[] = { 0, 0, 1, 15 };
static const unsigned char exception_start[] = { 0, 0, 1, 10 };
static const unsigned char exception_end[] = { 0, 0, 1, 11 };
static const unsigned char byte_start[] = { 0, 0, 1, 12 };
static const unsigned char byte_end[] = { 0, 0, 1, 13 };
DecompInterface::~DecompInterface() {
statusGood = false;
for (std::map<std::string, XmlPcodeEmit*>::iterator it = callFixupMap.begin();
it != callFixupMap.end(); it++) {
delete it->second;
}
for (std::map<std::string, XmlPcodeEmit*>::iterator it = callFixupOtherMap.begin();
it != callFixupOtherMap.end(); it++) {
delete it->second;
}
for (std::map<std::string, XmlPcodeEmit*>::iterator it = callMechMap.begin();
it != callMechMap.end(); it++) {
delete it->second;
}
for (std::map<std::string, XmlPcodeEmit*>::iterator it = callExecPcodeMap.begin();
it != callExecPcodeMap.end(); it++) {
delete it->second;
}
if (trans != nullptr) delete trans;
if (context != nullptr) delete context;
if (loader != nullptr) delete loader;
}
uchar DecompInterface::read()
{
uchar cur;
if (callback->readDec(&cur, 1) <= 0) throw DecompError("Read pipe is bad");
return cur;
}
void DecompInterface::write(void const* Buf, size_t MaxCharCount)
{
if (callback->writeDec(Buf, MaxCharCount) < 0) throw DecompError("Write pipe is bad");
}
uchar DecompInterface::readToBurst() {
uchar cur;
for (;;) {
do {
cur = read();
} while (cur > 0);
if (cur == -1) {
break;
}
do {
cur = read();
} while (cur == 0);
if (cur == 1) {
cur = read();
if (cur == -1) {
break;
}
return cur;
}
if (cur == -1) {
break;
}
}
throw DecompError("Decompiler process died");
return -1;
}
uchar DecompInterface::readToBuffer(std::vector<uchar>& buf) {
uchar cur;
for (;;) {
cur = read();
while (cur > 0) {
if (buf.size() >= (maxResultSizeMBYtes << 20))
throw DecompError("Maximum payload size exceeded");
buf.push_back((uchar)cur);
cur = read();
}
if (cur == -1) {
break;
}
do {
cur = read();
} while (cur == 0);
if (cur == 1) {
cur = read();
if (cur > 0) {
return cur;
}
}
if (cur == -1) {
break;
}
}
throw DecompError("Decompiler process died");
return -1;
}
std::string DecompInterface::readQueryString() {
int type = readToBurst();
if (type != 14) {
throw DecompError("GHIDRA/decompiler alignment error");
}
std::vector<uchar> buf; //new LimitedByteBuffer(16, 1 << 16);
type = readToBuffer(buf);
if (type != 15) {
throw DecompError("GHIDRA/decompiler alignment error");
}
return std::string(buf.begin(), buf.end());
}
void DecompInterface::generateException() {
std::string type = readQueryString();
std::string message = readQueryString();
callback->protocolRecorder("exception(\"" + escapeCStr(type) + "\", \"" + escapeCStr(message) + "\")", false);
readToBurst(); // Read exception terminator
if (type == "alignment") {
throw DecompError("Alignment error: " + message);
}
throw DecompError(type + " " + message);
}
void DecompInterface::readToResponse() {
//device level descriptors are not buffered and do not need flushing
//fflush(nativeOut); // Make sure decompiler has access to all the info it has been sent
uchar type;
do {
type = readToBurst();
} while ((type & 1) == 1);
if (type == 10) {
generateException();
}
if (type == 6) {
return;
}
throw DecompError("Ghidra/decompiler alignment error");
}
void DecompInterface::writeString(std::string msg) {
write(string_start, sizeof(string_start));
write(msg.c_str(), (unsigned int)msg.size());
write(string_end, sizeof(string_end));
}
/**
* Transfer bytes written to -out- to decompiler process
* @param out has the collected byte for this write
*/
void DecompInterface::writeBytes(const uchar out[], int outlen) {
write(string_start, sizeof(string_start));
int sz = outlen;
uchar sz1 = (sz & 0x3f) + 0x20;
sz >>= 6;
uchar sz2 = (sz & 0x3f) + 0x20;
sz >>= 6;
uchar sz3 = (sz & 0x3f) + 0x20;
sz >>= 6;
uchar sz4 = (sz & 0x3f) + 0x20;
write(&sz1, sizeof(uchar));
write(&sz2, sizeof(uchar));
write(&sz3, sizeof(uchar));
write(&sz4, sizeof(uchar));
write(out, outlen);
write(string_end, sizeof(string_end));
}
//Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/pcode/PcodeDataTypeManager.java
std::string DecompInterface::buildTypeXml(std::vector<TypeInfo>& ti, size_t indnt)
{
std::string str;
std::stack<int> s;
s.push(0);
while (!s.empty()) {
int idx = s.top();
s.pop();
if (idx < 0) { //-1 used to indicate coming back up the stack for ptr and array
str += std::string(indnt + ~idx * 2, ' ') + "</type>\n";
continue;
}
TypeInfo& typeInfo = ti.at(idx);
//if (typeInfo == terminate) return ""; //termination happens at appropriate place implicitly
if (typeInfo.size == -1) {
/*int i;
for (i = 0; i < numDefCoreTypes; i++) {
if (defaultCoreTypes[i].name == typeInfo.typeName) break;
} // - (i == numDefCoreTypes ? (1ull << 63) : 0) */
str += std::string(indnt + idx * 2, ' ') + "<typeref name=\"" + typeInfo.typeName + "\" id=\"0x" +
to_string(hashName(typeInfo.typeName), hex) + "\"/>\n"; //terminates
continue;
}
if (typeInfo.metaType == "ptr") {
str += std::string(indnt + idx * 2, ' ') + "<type name=\"" + typeInfo.typeName + /*"\" id=\"" + std::to_string(hashName(typeInfo.typeName))*/ +
"\" metatype=\"" + typeInfo.metaType +
"\" size=\"" + std::to_string(typeInfo.size) + "\">\n"; //wordsize=\"\" when != 1
s.push(~idx);
s.push(idx + 1);
} else if (typeInfo.metaType == "struct") {
std::string strct;
for (int i = 0; i < typeInfo.structMembers.size(); i++) { //core types are not type referenced though
strct += std::string(indnt + idx * 2 + 2, ' ') + "<field name=\"" + typeInfo.structMembers[i].name +
"\" offset=\"" +
std::to_string(typeInfo.structMembers[i].offset) + "\">\n" +
buildTypeXml(typeInfo.structMembers[i].ti, indnt + idx * 2 + 4) + std::string(indnt + idx * 2 + 2, ' ') + "</field>\n";
}
str += std::string(indnt + idx * 2, ' ') + "<type name=\"" + typeInfo.typeName +
"\" id=\"" + std::to_string(hashName(typeInfo.typeName)) +
"\" metatype=\"" + typeInfo.metaType + "\" size=\"" +
std::to_string(typeInfo.size) + "\">\n" + strct + std::string(indnt + idx * 2, ' ') + "</type>\n"; //terminates
} else if (typeInfo.metaType == "array") {
str += std::string(indnt + idx * 2, ' ') + "<type name=\"" + typeInfo.typeName +
"\" metatype=\"" + typeInfo.metaType + "\" size=\"" +
std::to_string(typeInfo.size) +
"\" arraysize=\"" + std::to_string(typeInfo.arraySize) + "\">\n";
s.push(~idx);
s.push(idx + 1);
} else if (typeInfo.metaType == "code") {
str += std::string(indnt + idx * 2, ' ') + "<type name=\"" + typeInfo.typeName +
"\" id=\"" + std::to_string(hashName(typeInfo.typeName)) +
"\" metatype=\"" + typeInfo.metaType +
"\" size=\"" + std::to_string(typeInfo.size) + "\">\n" +
writeFuncProto(typeInfo.funcInfo, "", true, indnt + idx * 2 + 2) +
std::string(indnt + idx * 2, ' ') + "</type>\n";
} else if (typeInfo.metaType == "void") {
str += std::string(indnt + idx * 2, ' ') + "<void/>\n";
} else {
/*int i;
for (i = 0; i < numDefCoreTypes; i++) {
if (defaultCoreTypes[i].name == typeInfo.typeName) break;
} // - (i == numDefCoreTypes ? (1ull << 63) : 0)*/
str += std::string(indnt, ' ') + "<type name=\"" + typeInfo.typeName +
"\" id=\"" + std::to_string(hashName(typeInfo.typeName)) +
"\" metatype=\"" + typeInfo.metaType +
"\" size=\"" + std::to_string(typeInfo.size) + "\"" +
std::string(typeInfo.isEnum ? " enum=\"true\"" : "") +
std::string(typeInfo.isUtf ? " utf=\"true\"" : "") +
std::string(typeInfo.isChar ? " char=\"true\"" : "") +
">\n"; //core=\"true\"
if (typeInfo.isEnum) {
for (size_t i = 0; i < typeInfo.enumMembers.size(); i++) {
str += std::string(indnt + 2, ' ') + "<val name=\"" + typeInfo.enumMembers[i].first +
"\" value=\"" + std::to_string(typeInfo.enumMembers[i].second) + "\"/>\n";
}
}
str += std::string(indnt, ' ') + "</type>\n";
}
//metaType == "uint" && callback->isEnum();
//metaType == "code"...
}
return str;
}
enum comment_type {
user1 = 1, ///< The first user defined property
user2 = 2, ///< The second user defined property
user3 = 4, ///< The third user defined property
header = 8, ///< The comment should be displayed in the function header
warning = 16, ///< The comment is auto-generated to alert the user
warningheader = 32 ///< The comment is auto-generated and should be in the header
};
void DecompInterface::adjustUniqueBase(VarnodeTpl* v) {
if (v->getSpace().isUniqueSpace()) {
ConstTpl c = v->getOffset();
uintb offset = c.getReal();
if (offset >= uniqueBase) uniqueBase = offset + 16;
}
}
//Ghidra/Features/Decompiler/src/main/java/ghidra/app/decompiler/DecompileCallback.java
//Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/lang/PcodeInjectLibrary.java
XmlPcodeEmit* DecompInterface::getPcodeSnippet(std::string parsestring,
const std::vector<std::pair<std::string, int>>& inputs,
const std::vector<std::pair<std::string, int>>& outputs)
{
PcodeSnippet compiler(trans);
// compiler.clear(); // Not necessary unless we reuse
compiler.setUniqueBase(uniqueBase);
istringstream s(parsestring);
for (size_t i = 0; i < inputs.size(); i++)
compiler.addOperand(inputs[i].first, inputs[i].second);
for (size_t i = 0; i < outputs.size(); i++)
compiler.addOperand(outputs[i].first, outputs[i].second);
if (!compiler.parseStream(s))
throw DecompError("Unable to compile pcode: " + compiler.getErrorMessage());
//uintm tempbase = compiler.getUniqueBase();
ConstructTpl* tpl = compiler.releaseResult();
//parsestring = ""; // No longer need the memory
//adjustUniqueBase
for (int i = 0; i < tpl->getOpvec().size(); i++) {
if (tpl->getOpvec()[i]->getOut() != nullptr)
adjustUniqueBase(tpl->getOpvec()[i]->getOut());
for (int j = 0; j < tpl->getOpvec()[i]->numInput(); j++)
adjustUniqueBase(tpl->getOpvec()[i]->getIn(j));
}
//buildInstruction
ContextInternal cdb;
ContextCache cc(&cdb);
//use PcodeCacher to resolve issues
XmlPcodeEmit* emit = new XmlPcodeEmit();
uint4 parser_cachesize = 2;
uint4 parser_windowsize = 32;
DisassemblyCache discache(&cc, trans->getConstantSpace(), parser_cachesize, parser_windowsize);
ParserContext* pc = discache.getParserContext(Address());
//ParserContext pc(&cc); //Java derives a SleighParserContext
//Create state suitable for parsing a just a p-code semantics snippet
ParserWalkerChange walker(pc);
walker.baseState();
Constructor c(nullptr);
walker.setConstructor(&c);
//int4 curstate = pos->getParserState();
//if (curstate == ParserContext::uninitialized) resolve(*pos);
// If we reach here, state must be ParserContext::pcode
//resolveHandles(*pos);
PcodeCacher pcode_cache;
//walker.snippetState();
//the whole task here is to glue the construction template to the walker through the context
//trans->oneInstruction(emit, Address(trans->getSpaceByName(space), addr)); //Sleigh not sufficient for ConstructTpl...
SleighBuilder builder(&walker, &discache, &pcode_cache,
trans->getConstantSpace(), trans->getUniqueSpace(), 0); //unique_allocatemask not used and always 0
//now tie input and output parameters for all callfixupother, callmechanism, executablepcode
try {
builder.build(tpl, -1);
pcode_cache.resolveRelatives();
pcode_cache.emit(Address(), emit);
} catch (SleighError& err) {
delete emit;
throw DecompError(err.explain.c_str());
} catch (BadDataError& err) {
delete emit;
throw DecompError(err.explain.c_str());
} catch (UnimplError& /*err*/) {
ostringstream s;
s << "Instruction not implemented in pcode:\n ";
ParserWalker* cur = builder.getCurrentWalker();
cur->baseState();
Constructor* ct = cur->getConstructor();
cur->getAddr().printRaw(s);
s << ": ";
ct->printMnemonic(s, *cur);
s << " ";
ct->printBody(s, *cur);
//err.explain = s.str();
//err.instruction_length = fallOffset;
delete emit;
throw DecompError(s.str());
} catch (LowlevelError& err) {
delete emit;
throw DecompError(err.explain.c_str());
}
return emit;
}
std::string DecompInterface::compilePcodeSnippet(std::string sleighfilename,
std::string parsestring,
const std::vector<std::pair<std::string, int>>& inputs,
const std::vector<std::pair<std::string, int>>& outputs)
{
DecompInterface* di = new DecompInterface();
di->setupTranslator(nullptr, sleighfilename);
XmlPcodeEmit* emit = di->getPcodeSnippet(parsestring, inputs, outputs);
std::string str = emit->build("ram", 0x10000000);
delete di;
return str;
}
void getAddrFromString(std::string addrstring, AddrInfo& addr, unsigned long long* size)
{
istringstream str(addrstring);
Document* doc;
try {
doc = xml_tree(str);
} catch (XmlError&) {
throw DecompError("Received bad XML Address from decompiler");
}
Element* el = doc->getRoot();
addr.space = el->getAttributeValue("space");
addr.offset = strtoull(el->getAttributeValue("offset").c_str(), nullptr, 16);
if (size != nullptr) *size = strtoll(el->getAttributeValue("size").c_str(), nullptr, 10);
delete doc;
}
void getAddrFromString(std::string addrstring, AddrInfo & addr)
{
getAddrFromString(addrstring, addr, nullptr);
}
void getAddrFromString(std::string addrstring, SizedAddrInfo& addr)
{
getAddrFromString(addrstring, addr.addr, &addr.size);
}
void DecompInterface::processPcodeInject(int type, std::map<std::string, XmlPcodeEmit*> &fixupmap)
{
std::string name = readQueryString(); //inject_sleigh.cc
std::string context = readQueryString();
std::string types[] = { "getCallFixup", "getCallotherFixup", "getCallMech", "getXPcode" };
callback->protocolRecorder("query(\"" + escapeCStr(types[type - 1]) + "\", \"" + escapeCStr(name) + "\", \"" + escapeCStr(context) + "\")", false);
istringstream str(context);
Document* doc;
try {
doc = xml_tree(str);
} catch (XmlError&) {
throw DecompError("Received bad XML inject context from decompiler");
}
Element* el = doc->getRoot();
const List& list(el->getChildren());
List::const_iterator iter;
bool bFirst = true;
std::string space, offset, fixupspace, fixupoffset; //first address for current address, next for fixup
for (iter = list.begin(); iter != list.end(); ++iter) {
el = *iter;
if (el->getName() == "addr") { //should only be 2 of them
for (int i = 0; i < el->getNumAttributes(); i++) {
if (el->getAttributeName(i) == "space")
(bFirst ? space : fixupspace) = el->getAttributeValue(i);
else if (el->getAttributeName(i) == "offset")
(bFirst ? offset : fixupoffset) = el->getAttributeValue(i);
}
bFirst = !bFirst;
}
}
delete doc;
uint8 idx = strtoull(offset.c_str(), nullptr, 16);
uint8 fixupidx = strtoull(fixupoffset.c_str(), nullptr, 16);
XmlPcodeEmit* emitter = fixupmap[name];
if (fixupmap[name]->strs.size() == 0) //dynamic, has no body
emitter = getPcodeSnippet(callback->getPcodeInject(type, name,
AddrInfo{ space, idx }, fixupspace, fixupidx),
emitter->inputs, emitter->outputs);
std::string s = "<inst" " offset=\"" +
std::to_string(trans->instructionLength(Address(trans->getSpaceByName(space), idx))) + "\"" +
std::string(emitter->paramShift != 0 ? "paramshift=\"" +
std::to_string(emitter->paramShift) + "\"" : "") + ">\n" +
emitter->build(space, idx) + "</inst>\n";
write(query_response_start, sizeof(query_response_start));
writeString(s);
write(query_response_end, sizeof(query_response_end));
callback->protocolRecorder("queryresponse(\"" + escapeCStr(s) + "\")", true);
if (fixupmap[name] == nullptr) delete emitter;
}
std::string DecompInterface::writeFuncProto(FuncProtoInfo func,
std::string injectstr, bool bUseInternalList, size_t indnt)
{
std::string symbols;
std::string joinString;
if (callStyles.find(func.model) == callStyles.end()) func.model = "unknown";
if (bUseInternalList) {
for (std::vector<SymInfo>::iterator it = func.syminfo.begin(); it != func.syminfo.end(); it++) {
bool readonly = false;
symbols += std::string(indnt + 4, ' ') + "<param name=\"" + it->pi.name + "\" typelock=\"" "true"
"\" namelock=\"" + std::string(it->pi.name.size() != 0 ? "true" : "false") + "\">\n" +
std::string(indnt + 6, ' ') + "<addr/>\n" +
buildTypeXml(it->pi.ti, indnt + 6) +
std::string(indnt + 4, ' ') + "</param>\n"; //"<type name=\"\" metatype=\"" + "\" size=\"" "\"><typeref name=\"" + it->typeRef + "\" id=\"" + std::string(buf) "\"/></type>"
}
} else {
if (func.retType.addr.addr.space == "join") {
for (int i = 0; i < func.retType.addr.addr.joins.size(); i++) {
if (i != 0) joinString += " ";
joinString += "piece" + std::to_string(i + 1) +
"=\"" + func.retType.addr.addr.joins[i].addr.space + ":0x" +
to_string(func.retType.addr.addr.joins[i].addr.offset) + ":" +
std::to_string(func.retType.addr.addr.joins[i].size) + "\"";
}
}
}
std::string killbycall;
if (func.killedByCall.size() != 0) {
killbycall = std::string(indnt + 2, ' ') + "<killedbycall>\n";
for (size_t i = 0; i < func.killedByCall.size(); i++) {
killbycall += std::string(indnt + 4, ' ') + "<addr space=\"" + func.killedByCall[i].addr.space +
"\" offset=\"0x" + to_string(func.killedByCall[i].addr.offset, hex) +
"\" size=\"" + std::to_string(func.killedByCall[i].size) + "\"/>\n";
}
killbycall += std::string(indnt + 2, ' ') + "</killedbycall>\n";
}
return std::string(indnt, ' ') + "<prototype extrapop=\"" +
(func.extraPop != -1 ? std::to_string(func.extraPop) : std::string("unknown")) +
"\" model=\"" + func.model + "\" modellock=\"" +
(func.model != "default" && func.model != "unknown" && lastdm.actionname != "paramid" ? "true" : "false") +
(func.model != "default" && func.model != "unknown" && lastdm.actionname != "paramid" && func.syminfo.size() == 0 ?
"\" voidlock=\"true" : "") +
(func.isInline ? "\" inline=\"true" : "") +
(func.isNoReturn ? "\" noreturn=\"true" : "") +
(func.hasThis ? "\" hasthis=\"true" : "") +
(func.customStorage ? "\" custom=\"true" : "") +
(func.isConstruct ? "\" constructor=\"true" : "") +
(func.isDestruct ? "\" destructor=\"true" : "") +
(func.dotdotdot ? "\" dotdotdot=\"true" : "") +
"\">\n" +
std::string(indnt + 2, ' ') + "<returnsym" +
std::string(func.retType.pi.ti.begin()->metaType != "unknown" && lastdm.actionname != "paramid" ? " typelock=\"true\"" : "") +
">\n" +
std::string(func.retType.addr.size == 0 ? std::string(indnt + 4, ' ') + "<addr/>\n" + std::string(indnt + 4, ' ') + "<void/>\n" :
((bUseInternalList ? std::string(indnt + 4, ' ') + "<addr/>\n" :
std::string(indnt + 4, ' ') + "<addr space=\"" + func.retType.addr.addr.space + "\" " +
(func.retType.addr.addr.space != "join" ? "offset=\"0x" +
to_string(func.retType.addr.addr.offset, hex) +