forked from cseagle/blc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprintc.cc
3378 lines (3105 loc) · 104 KB
/
printc.cc
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
/* ###
* IP: GHIDRA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "printc.hh"
#include "funcdata.hh"
namespace ghidra {
// Operator tokens for expressions
// token #in prec assoc optype space bump
OpToken PrintC::hidden = { "", "", 1, 70, false, OpToken::hiddenfunction, 0, 0, (OpToken *)0 };
OpToken PrintC::scope = { "::", "", 2, 70, true, OpToken::binary, 0, 0, (OpToken *)0 };
OpToken PrintC::object_member = { ".", "", 2, 66, true, OpToken::binary, 0, 0, (OpToken *)0 };
OpToken PrintC::pointer_member = { "->", "", 2, 66, true, OpToken::binary, 0, 0, (OpToken *)0 };
OpToken PrintC::subscript = { "[", "]", 2, 66, false, OpToken::postsurround, 0, 0, (OpToken *)0 };
OpToken PrintC::function_call = { "(", ")", 2, 66, false, OpToken::postsurround, 0, 10, (OpToken *)0 };
OpToken PrintC::bitwise_not = { "~", "", 1, 62, false, OpToken::unary_prefix, 0, 0, (OpToken *)0 };
OpToken PrintC::boolean_not = { "!", "", 1, 62, false, OpToken::unary_prefix, 0, 0, (OpToken *)0 };
OpToken PrintC::unary_minus = { "-", "", 1, 62, false, OpToken::unary_prefix, 0, 0, (OpToken *)0 };
OpToken PrintC::unary_plus = { "+", "", 1, 62, false, OpToken::unary_prefix, 0, 0, (OpToken *)0 };
OpToken PrintC::addressof = { "&", "", 1, 62, false, OpToken::unary_prefix, 0, 0, (OpToken *)0 };
OpToken PrintC::dereference = { "*", "", 1, 62, false, OpToken::unary_prefix, 0, 0, (OpToken *)0 };
OpToken PrintC::typecast = { "(", ")", 2, 62, false, OpToken::presurround, 0, 0, (OpToken *)0 };
OpToken PrintC::multiply = { "*", "", 2, 54, true, OpToken::binary, 1, 0, (OpToken *)0 };
OpToken PrintC::divide = { "/", "", 2, 54, false, OpToken::binary, 1, 0, (OpToken *)0 };
OpToken PrintC::modulo = { "%", "", 2, 54, false, OpToken::binary, 1, 0, (OpToken *)0 };
OpToken PrintC::binary_plus = { "+", "", 2, 50, true, OpToken::binary, 1, 0, (OpToken *)0 };
OpToken PrintC::binary_minus = { "-", "", 2, 50, false, OpToken::binary, 1, 0, (OpToken *)0 };
OpToken PrintC::shift_left = { "<<", "", 2, 46, false, OpToken::binary, 1, 0, (OpToken *)0 };
OpToken PrintC::shift_right = { ">>", "", 2, 46, false, OpToken::binary, 1, 0, (OpToken *)0 };
OpToken PrintC::shift_sright = { ">>", "", 2, 46, false, OpToken::binary, 1, 0, (OpToken *)0 };
OpToken PrintC::less_than = { "<", "", 2, 42, false, OpToken::binary, 1, 0, (OpToken *)0 };
OpToken PrintC::less_equal = { "<=", "", 2, 42, false, OpToken::binary, 1, 0, (OpToken *)0 };
OpToken PrintC::greater_than = { ">", "", 2, 42, false, OpToken::binary, 1, 0, (OpToken *)0 };
OpToken PrintC::greater_equal = { ">=", "", 2, 42, false, OpToken::binary, 1, 0, (OpToken *)0 };
OpToken PrintC::equal = { "==", "", 2, 38, false, OpToken::binary, 1, 0, (OpToken *)0 };
OpToken PrintC::not_equal = { "!=", "", 2, 38, false, OpToken::binary, 1, 0, (OpToken *)0 };
OpToken PrintC::bitwise_and = { "&", "", 2, 34, true, OpToken::binary, 1, 0, (OpToken *)0 };
OpToken PrintC::bitwise_xor = { "^", "", 2, 30, true, OpToken::binary, 1, 0, (OpToken *)0 };
OpToken PrintC::bitwise_or = { "|", "", 2, 26, true, OpToken::binary, 1, 0, (OpToken *)0 };
OpToken PrintC::boolean_and = { "&&", "", 2, 22, false, OpToken::binary, 1, 0, (OpToken *)0 };
OpToken PrintC::boolean_xor = { "^^", "", 2, 20, false, OpToken::binary, 1, 0, (OpToken *)0 };
OpToken PrintC::boolean_or = { "||", "", 2, 18, false, OpToken::binary, 1, 0, (OpToken *)0 };
OpToken PrintC::assignment = { "=", "", 2, 14, false, OpToken::binary, 1, 5, (OpToken *)0 };
OpToken PrintC::comma = { ",", "", 2, 2, true, OpToken::binary, 0, 0, (OpToken *)0 };
OpToken PrintC::new_op = { "", "", 2, 62, false, OpToken::space, 1, 0, (OpToken *)0 };
// Inplace assignment operators
OpToken PrintC::multequal = { "*=", "", 2, 14, false, OpToken::binary, 1, 5, (OpToken *)0 };
OpToken PrintC::divequal = { "/=", "", 2, 14, false, OpToken::binary, 1, 5, (OpToken *)0 };
OpToken PrintC::remequal = { "%=", "", 2, 14, false, OpToken::binary, 1, 5, (OpToken *)0 };
OpToken PrintC::plusequal = { "+=", "", 2, 14, false, OpToken::binary, 1, 5, (OpToken *)0 };
OpToken PrintC::minusequal = { "-=", "", 2, 14, false, OpToken::binary, 1, 5, (OpToken *)0 };
OpToken PrintC::leftequal = { "<<=", "", 2, 14, false, OpToken::binary, 1, 5, (OpToken *)0 };
OpToken PrintC::rightequal = { ">>=", "", 2, 14, false, OpToken::binary, 1, 5, (OpToken *)0 };
OpToken PrintC::andequal = { "&=", "", 2, 14, false, OpToken::binary, 1, 5, (OpToken *)0 };
OpToken PrintC::orequal = { "|=", "", 2, 14, false, OpToken::binary, 1, 5, (OpToken *)0 };
OpToken PrintC::xorequal = { "^=", "", 2, 14, false, OpToken::binary, 1, 5, (OpToken *)0 };
// Operator tokens for type expressions
OpToken PrintC::type_expr_space = { "", "", 2, 10, false, OpToken::space, 1, 0, (OpToken *)0 };
OpToken PrintC::type_expr_nospace = { "", "", 2, 10, false, OpToken::space, 0, 0, (OpToken *)0 };
OpToken PrintC::ptr_expr = { "*", "", 1, 62, false, OpToken::unary_prefix, 0, 0, (OpToken *)0 };
OpToken PrintC::array_expr = { "[", "]", 2, 66, false, OpToken::postsurround, 1, 0, (OpToken *)0 };
OpToken PrintC::enum_cat = { "|", "", 2, 26, true, OpToken::binary, 0, 0, (OpToken *)0 };
const string PrintC::EMPTY_STRING = "";
const string PrintC::OPEN_CURLY = "{";
const string PrintC::CLOSE_CURLY = "}";
const string PrintC::SEMICOLON = ";";
const string PrintC::COLON = ":";
const string PrintC::EQUALSIGN = "=";
const string PrintC::COMMA = ",";
const string PrintC::DOTDOTDOT = "...";
const string PrintC::KEYWORD_VOID = "void";
const string PrintC::KEYWORD_TRUE = "true";
const string PrintC::KEYWORD_FALSE = "false";
const string PrintC::KEYWORD_IF = "if";
const string PrintC::KEYWORD_ELSE = "else";
const string PrintC::KEYWORD_DO = "do";
const string PrintC::KEYWORD_WHILE = "while";
const string PrintC::KEYWORD_FOR = "for";
const string PrintC::KEYWORD_GOTO = "goto";
const string PrintC::KEYWORD_BREAK = "break";
const string PrintC::KEYWORD_CONTINUE = "continue";
const string PrintC::KEYWORD_CASE = "case";
const string PrintC::KEYWORD_SWITCH = "switch";
const string PrintC::KEYWORD_DEFAULT = "default";
const string PrintC::KEYWORD_RETURN = "return";
const string PrintC::KEYWORD_NEW = "new";
const string PrintC::typePointerRelToken = "ADJ";
// Constructing this registers the capability
PrintCCapability PrintCCapability::printCCapability;
PrintCCapability::PrintCCapability(void)
{
name = "c-language";
isdefault = true;
}
PrintLanguage *PrintCCapability::buildLanguage(Architecture *glb)
{
return new PrintC(glb,name);
}
/// \param g is the Architecture owning this c-language emitter
/// \param nm is the name assigned to this emitter
PrintC::PrintC(Architecture *g,const string &nm) : PrintLanguage(g,nm)
{
nullToken = "NULL";
// Set the flip tokens
less_than.negate = &greater_equal;
less_equal.negate = &greater_than;
greater_than.negate = &less_equal;
greater_equal.negate = &less_than;
equal.negate = ¬_equal;
not_equal.negate = &equal;
castStrategy = new CastStrategyC();
resetDefaultsPrintC();
}
/// Push nested components of a data-type declaration onto a stack, so we can access it bottom up
/// \param ct is the data-type being emitted
/// \param typestack will hold the sub-types involved in the displaying the declaration
void PrintC::buildTypeStack(const Datatype *ct,vector<const Datatype *> &typestack)
{
for(;;) {
typestack.push_back(ct);
if (ct->getName().size() != 0) // This can be a base type
break;
if (ct->getMetatype()==TYPE_PTR)
ct = ((TypePointer *)ct)->getPtrTo();
else if (ct->getMetatype()==TYPE_ARRAY)
ct = ((TypeArray *)ct)->getBase();
else if (ct->getMetatype()==TYPE_CODE) {
const FuncProto *proto = ((TypeCode *)ct)->getPrototype();
if (proto != (const FuncProto *)0)
ct = proto->getOutputType();
else
ct = glb->types->getTypeVoid();
}
else
break; // Some other anonymous type
}
}
/// Push the comma separated list of data-type declarations onto the RPN stack as
/// part of emitting a given function prototype
/// \param proto is the given function prototype
void PrintC::pushPrototypeInputs(const FuncProto *proto)
{
int4 sz = proto->numParams();
if ((sz == 0)&&(!proto->isDotdotdot()))
pushAtom(Atom(KEYWORD_VOID,syntax,EmitMarkup::keyword_color));
else {
for(int4 i=0;i<sz-1;++i)
pushOp(&comma,(const PcodeOp *)0); // Print a comma for each parameter (above 1)
if (proto->isDotdotdot()&&(sz!=0)) // Print comma for dotdotdot (if it is not by itself)
pushOp(&comma,(const PcodeOp *)0);
for(int4 i=0;i<sz;++i) {
ProtoParameter *param = proto->getParam(i);
pushTypeStart(param->getType(),true);
pushAtom(Atom(EMPTY_STRING,blanktoken,EmitMarkup::no_color));
pushTypeEnd(param->getType());
}
if (proto->isDotdotdot()) {
if (sz != 0)
pushAtom(Atom(DOTDOTDOT,syntax,EmitMarkup::no_color));
else {
// In ANSI C, a prototype with empty parens means the parameters are unspecified (not void)
// In C++, empty parens mean void, we use the ANSI C convention
pushAtom(Atom(EMPTY_STRING,blanktoken,EmitMarkup::no_color)); // An empty list of parameters
}
}
}
}
/// Calculate what elements of a given symbol's namespace path are necessary to distinguish
/// it within the current scope. Then print these elements.
/// \param symbol is the given symbol
void PrintC::pushSymbolScope(const Symbol *symbol)
{
int4 scopedepth;
if (namespc_strategy == MINIMAL_NAMESPACES)
scopedepth = symbol->getResolutionDepth(curscope);
else if (namespc_strategy == ALL_NAMESPACES) {
if (symbol->getScope() == curscope)
scopedepth = 0;
else
scopedepth = symbol->getResolutionDepth((const Scope *)0);
}
else
scopedepth = 0;
if (scopedepth != 0) {
vector<const Scope *> scopeList;
const Scope *point = symbol->getScope();
for(int4 i=0;i<scopedepth;++i) {
scopeList.push_back(point);
point = point->getParent();
pushOp(&scope, (PcodeOp *)0);
}
for(int4 i=scopedepth-1;i>=0;--i) {
pushAtom(Atom(scopeList[i]->getDisplayName(),syntax,EmitMarkup::global_color,(PcodeOp *)0,(Varnode *)0));
}
}
}
/// Emit the elements of the given symbol's namespace path that distinguish it within
/// the current scope.
/// \param symbol is the given Symbol
void PrintC::emitSymbolScope(const Symbol *symbol)
{
int4 scopedepth;
if (namespc_strategy == MINIMAL_NAMESPACES)
scopedepth = symbol->getResolutionDepth(curscope);
else if (namespc_strategy == ALL_NAMESPACES) {
if (symbol->getScope() == curscope)
scopedepth = 0;
else
scopedepth = symbol->getResolutionDepth((const Scope *)0);
}
else
scopedepth = 0;
if (scopedepth != 0) {
vector<const Scope *> scopeList;
const Scope *point = symbol->getScope();
for(int4 i=0;i<scopedepth;++i) {
scopeList.push_back(point);
point = point->getParent();
}
for(int4 i=scopedepth-1;i>=0;--i) {
emit->print(scopeList[i]->getDisplayName(), EmitMarkup::global_color);
emit->print(scope.print1, EmitMarkup::no_color);
}
}
}
/// Store off array sizes for printing after the identifier
/// \param ct is the data-type to push
/// \param noident is \b true if an identifier will not be pushed as part of the declaration
void PrintC::pushTypeStart(const Datatype *ct,bool noident)
{
// Find the root type (the one with an identifier) and layout
// the stack of types, so we can access in reverse order
vector<const Datatype *> typestack;
buildTypeStack(ct,typestack);
ct = typestack.back(); // The base type
OpToken *tok;
if (noident && (typestack.size()==1))
tok = &type_expr_nospace;
else
tok = &type_expr_space;
if (ct->getName().size()==0) { // Check for anonymous type
// We could support a struct or enum declaration here
string nm = genericTypeName(ct);
pushOp(tok,(const PcodeOp *)0);
pushAtom(Atom(nm,typetoken,EmitMarkup::type_color,ct));
}
else {
pushOp(tok,(const PcodeOp *)0);
pushAtom(Atom(ct->getDisplayName(),typetoken,EmitMarkup::type_color,ct));
}
for(int4 i=typestack.size()-2;i>=0;--i) {
ct = typestack[i];
if (ct->getMetatype() == TYPE_PTR)
pushOp(&ptr_expr,(const PcodeOp *)0);
else if (ct->getMetatype() == TYPE_ARRAY)
pushOp(&array_expr,(const PcodeOp *)0);
else if (ct->getMetatype() == TYPE_CODE)
pushOp(&function_call,(const PcodeOp *)0);
else {
clear();
throw LowlevelError("Bad type expression");
}
}
}
/// Because the front-ends were pushed on
/// base-type -> final-modifier, the tail-ends are pushed on
/// final-modifier -> base-type.
/// The tail-ends amount to
/// - array subscripts . [ # ] and
/// - function parameters . ( paramlist )
///
/// \param ct is the data-type being pushed
void PrintC::pushTypeEnd(const Datatype *ct)
{
pushMod();
setMod(force_dec);
for(;;) {
if (ct->getName().size() != 0) // This is the base type
break;
if (ct->getMetatype()==TYPE_PTR)
ct = ((const TypePointer *)ct)->getPtrTo();
else if (ct->getMetatype()==TYPE_ARRAY) {
const TypeArray *ctarray = (const TypeArray *)ct;
ct = ctarray->getBase();
push_integer(ctarray->numElements(),4,false,syntax,
(const Varnode *)0,(const PcodeOp *)0);
}
else if (ct->getMetatype()==TYPE_CODE) {
const TypeCode *ctcode = (const TypeCode *)ct;
const FuncProto *proto = ctcode->getPrototype();
if (proto != (const FuncProto *)0) {
pushPrototypeInputs(proto);
ct = proto->getOutputType();
}
else
// An empty list of parameters
pushAtom(Atom(EMPTY_STRING,blanktoken,EmitMarkup::no_color));
}
else
break; // Some other anonymous type
}
popMod();
}
/// An expression involving a LOAD or STORE can sometimes be emitted using
/// \e array syntax (or \e field \e member syntax). This method determines
/// if this kind of syntax is appropriate or if a '*' operator is required.
/// \param vn is the root of the pointer expression (feeding into LOAD or STORE)
/// \return \b false if '*' syntax is required, \b true if some other syntax is used
bool PrintC::checkArrayDeref(const Varnode *vn) const
{
const PcodeOp *op;
if (!vn->isImplied()) return false;
if (!vn->isWritten()) return false;
op = vn->getDef();
if (op->code()==CPUI_SEGMENTOP) {
vn = op->getIn(2);
if (!vn->isImplied()) return false;
if (!vn->isWritten()) return false;
op = vn->getDef();
}
if ((op->code()!=CPUI_PTRSUB)&&(op->code()!=CPUI_PTRADD)) return false;
return true;
}
/// Check that the output data-type is a pointer to an array and then that
/// the second data-type is a pointer to the element type (of the array).
/// If this holds and the input variable represents a symbol with an \e array data-type,
/// return \b true.
/// \return \b true if the CAST can be rendered as '&'
bool PrintC::checkAddressOfCast(const PcodeOp *op) const
{
Datatype *dt0 = op->getOut()->getHighTypeDefFacing();
const Varnode *vnin = op->getIn(0);
Datatype *dt1 = vnin->getHighTypeReadFacing(op);
if (dt0->getMetatype() != TYPE_PTR || dt1->getMetatype() != TYPE_PTR)
return false;
const Datatype *base0 = ((const TypePointer *)dt0)->getPtrTo();
const Datatype *base1 = ((const TypePointer *)dt1)->getPtrTo();
if (base0->getMetatype() != TYPE_ARRAY)
return false;
int4 arraySize = base0->getSize();
base0 = ((const TypeArray *)base0)->getBase();
while(base0->getTypedef() != (Datatype *)0)
base0 = base0->getTypedef();
while(base1->getTypedef() != (Datatype *)0)
base1 = base1->getTypedef();
if (base0 != base1)
return false;
Datatype *symbolType = (Datatype *)0;
if (vnin->getSymbolEntry() != (SymbolEntry *)0 && vnin->getHigh()->getSymbolOffset() == -1) {
symbolType = vnin->getSymbolEntry()->getSymbol()->getType();
}
else if (vnin->isWritten()) {
const PcodeOp *ptrsub = vnin->getDef();
if (ptrsub->code() == CPUI_PTRSUB) {
Datatype *rootType = ptrsub->getIn(0)->getHighTypeReadFacing(ptrsub);
if (rootType->getMetatype() == TYPE_PTR) {
rootType = ((TypePointer *)rootType)->getPtrTo();
int8 off = ptrsub->getIn(1)->getOffset();
symbolType = rootType->getSubType(off, &off);
if (off != 0)
return false;
}
}
}
if (symbolType == (Datatype *)0)
return false;
if (symbolType->getMetatype() != TYPE_ARRAY || symbolType->getSize() != arraySize)
return false;
return true;
}
/// This is used for expression that require functional syntax, where the name of the
/// function is the name of the operator. The inputs to the p-code op form the roots
/// of the comma separated list of \e parameters within the syntax.
/// \param op is the given PcodeOp
void PrintC::opFunc(const PcodeOp *op)
{
pushOp(&function_call,op);
// Using function syntax but don't markup the name as
// a normal function call
string nm = op->getOpcode()->getOperatorName(op);
pushAtom(Atom(nm,optoken,EmitMarkup::no_color,op));
if (op->numInput() > 0) {
for(int4 i=0;i<op->numInput()-1;++i)
pushOp(&comma,op);
// implied vn's pushed on in reverse order for efficiency
// see PrintLanguage::pushVnImplied
for(int4 i=op->numInput()-1;i>=0;--i)
pushVn(op->getIn(i),op,mods);
}
else // Push empty token for void
pushAtom(Atom(EMPTY_STRING,blanktoken,EmitMarkup::no_color));
}
/// The syntax represents the given op using a standard c-language cast. The data-type
/// being cast to is obtained from the output variable of the op. The input expression is
/// also recursively pushed.
/// \param op is the given PcodeOp
void PrintC::opTypeCast(const PcodeOp *op)
{
Datatype *dt = op->getOut()->getHighTypeDefFacing();
if (dt->isPointerToArray()) {
if (checkAddressOfCast(op)) {
pushOp(&addressof,op);
pushVn(op->getIn(0),op,mods);
return;
}
}
if (!option_nocasts) {
pushOp(&typecast,op);
pushType(dt);
}
pushVn(op->getIn(0),op,mods);
}
/// The syntax represents the given op using a function with one input,
/// where the function name is not printed. The input expression is simply printed
/// without adornment inside the larger expression, with one minor difference.
/// The hidden operator protects against confusing evaluation order between
/// the operators inside and outside the hidden function. If both the inside
/// and outside operators are the same associative token, the hidden token
/// makes sure the inner expression is surrounded with parentheses.
/// \param op is the given PcodeOp
void PrintC::opHiddenFunc(const PcodeOp *op)
{
pushOp(&hidden,op);
pushVn(op->getIn(0),op,mods);
}
void PrintC::opCopy(const PcodeOp *op)
{
pushVn(op->getIn(0),op,mods);
}
void PrintC::opLoad(const PcodeOp *op)
{
bool usearray = checkArrayDeref(op->getIn(1));
uint4 m = mods;
if (usearray&&(!isSet(force_pointer)))
m |= print_load_value;
else {
pushOp(&dereference,op);
}
pushVn(op->getIn(1),op,m);
}
void PrintC::opStore(const PcodeOp *op)
{
bool usearray;
// We assume the STORE is a statement
uint4 m = mods;
pushOp(&assignment,op); // This is an assignment
usearray = checkArrayDeref(op->getIn(1));
if (usearray && (!isSet(force_pointer)))
m |= print_store_value;
else {
pushOp(&dereference,op);
}
// implied vn's pushed on in reverse order for efficiency
// see PrintLanguage::pushVnImplied
pushVn(op->getIn(2),op,mods);
pushVn(op->getIn(1),op,m);
}
void PrintC::opBranch(const PcodeOp *op)
{
if (isSet(flat)) {
// Assume the BRANCH is a statement
emit->tagOp(KEYWORD_GOTO,EmitMarkup::keyword_color,op);
emit->spaces(1);
pushVn(op->getIn(0),op,mods);
}
}
/// Print the branching condition:
/// - If it is the first condition, print \b if
/// - If there is no block structure, print \b goto
///
/// \param op is the CBRANCH PcodeOp
void PrintC::opCbranch(const PcodeOp *op)
{
// FIXME: This routine shouldn't emit directly
bool yesif = isSet(flat);
bool yesparen = !isSet(comma_separate);
bool booleanflip = op->isBooleanFlip();
uint4 m = mods;
if (yesif) { // If not printing block structure
emit->tagOp(KEYWORD_IF,EmitMarkup::keyword_color,op);
emit->spaces(1);
if (op->isFallthruTrue()) { // and the fallthru is the true branch
booleanflip = !booleanflip; // print negation of condition
m |= falsebranch; // and print the false (non-fallthru) branch
}
}
int4 id;
if (yesparen)
id = emit->openParen(OPEN_PAREN);
else
id = emit->openGroup();
if (booleanflip) {
if (checkPrintNegation(op->getIn(1))) {
m |= PrintLanguage::negatetoken;
booleanflip = false;
}
}
if (booleanflip)
pushOp(&boolean_not,op);
pushVn(op->getIn(1),op,m);
// Make sure stack is clear before emitting more
recurse();
if (yesparen)
emit->closeParen(CLOSE_PAREN,id);
else
emit->closeGroup(id);
if (yesif) {
emit->spaces(1);
emit->print(KEYWORD_GOTO,EmitMarkup::keyword_color);
emit->spaces(1);
pushVn(op->getIn(0),op,mods);
}
}
void PrintC::opBranchind(const PcodeOp *op)
{
// FIXME: This routine shouldn't emit directly
emit->tagOp(KEYWORD_SWITCH,EmitMarkup::keyword_color,op); // Print header for switch
int4 id = emit->openParen(OPEN_PAREN);
pushVn(op->getIn(0),op,mods);
recurse();
emit->closeParen(CLOSE_PAREN,id);
}
void PrintC::opCall(const PcodeOp *op)
{
pushOp(&function_call,op);
const Varnode *callpoint = op->getIn(0);
FuncCallSpecs *fc;
if (callpoint->getSpace()->getType()==IPTR_FSPEC) {
fc = FuncCallSpecs::getFspecFromConst(callpoint->getAddr());
if (fc->getName().size()==0) {
string nm = genericFunctionName(fc->getEntryAddress());
pushAtom(Atom(nm,functoken,EmitMarkup::funcname_color,op,(const Funcdata *)0));
}
else {
Funcdata *fd = fc->getFuncdata();
if (fd != (Funcdata *)0)
pushSymbolScope(fd->getSymbol());
pushAtom(Atom(fc->getName(),functoken,EmitMarkup::funcname_color,op,(const Funcdata *)0));
}
}
else {
clear();
throw LowlevelError("Missing function callspec");
}
// TODO: Cannot hide "this" on a direct call until we print the whole
// thing with the proper C++ method invocation format. Otherwise the output
// gives no indication of what object has a method being called.
// int4 skip = getHiddenThisSlot(op, fc);
int4 skip = -1;
int4 count = op->numInput() - 1; // Number of parameter expressions printed
count -= (skip < 0) ? 0 : 1; // Subtract one if "this" is hidden
if (count > 0) {
for(int4 i=0;i<count-1;++i)
pushOp(&comma,op);
// implied vn's pushed on in reverse order for efficiency
// see PrintLanguage::pushVnImplied
for(int4 i=op->numInput()-1;i>=1;--i) {
if (i == skip) continue;
pushVn(op->getIn(i),op,mods);
}
}
else // Push empty token for void
pushAtom(Atom(EMPTY_STRING,blanktoken,EmitMarkup::no_color));
}
void PrintC::opCallind(const PcodeOp *op)
{
pushOp(&function_call,op);
pushOp(&dereference,op);
const Funcdata *fd = op->getParent()->getFuncdata();
FuncCallSpecs *fc = fd->getCallSpecs(op);
if (fc == (FuncCallSpecs *)0)
throw LowlevelError("Missing indirect function callspec");
int4 skip = getHiddenThisSlot(op, fc);
int4 count = op->numInput() - 1;
count -= (skip < 0) ? 0 : 1;
if (count > 1) { // Multiple parameters
pushVn(op->getIn(0),op,mods);
for(int4 i=0;i<count-1;++i)
pushOp(&comma,op);
// implied vn's pushed on in reverse order for efficiency
// see PrintLanguage::pushVnImplied
for(int4 i=op->numInput()-1;i>=1;--i) {
if (i == skip) continue;
pushVn(op->getIn(i),op,mods);
}
}
else if (count == 1) { // One parameter
if (skip == 1)
pushVn(op->getIn(2),op,mods);
else
pushVn(op->getIn(1),op,mods);
pushVn(op->getIn(0),op,mods);
}
else { // A void function
pushVn(op->getIn(0),op,mods);
pushAtom(Atom(EMPTY_STRING,blanktoken,EmitMarkup::no_color));
}
}
void PrintC::opCallother(const PcodeOp *op)
{
UserPcodeOp *userop = glb->userops.getOp(op->getIn(0)->getOffset());
uint4 display = userop->getDisplay();
if (display == UserPcodeOp::annotation_assignment) {
pushOp(&assignment,op);
pushVn(op->getIn(2),op,mods);
pushVn(op->getIn(1),op,mods);
}
else if (display == UserPcodeOp::no_operator) {
pushVn(op->getIn(1),op,mods);
}
else { // Emit using functional syntax
string nm = op->getOpcode()->getOperatorName(op);
pushOp(&function_call,op);
pushAtom(Atom(nm,optoken,EmitMarkup::funcname_color,op));
if (op->numInput() > 1) {
for(int4 i = 1;i < op->numInput() - 1;++i)
pushOp(&comma,op);
// implied vn's pushed on in reverse order for efficiency
// see PrintLanguage::pushVnImplied
for(int4 i = op->numInput() - 1;i >= 1;--i)
pushVn(op->getIn(i),op,mods);
}
else
pushAtom(Atom(EMPTY_STRING,blanktoken,EmitMarkup::no_color)); // Push empty token for void
}
}
void PrintC::opConstructor(const PcodeOp *op,bool withNew)
{
Datatype *dt;
if (withNew) {
const PcodeOp *newop = op->getIn(1)->getDef();
const Varnode *outvn = newop->getOut();
pushOp(&new_op,newop);
pushAtom(Atom(KEYWORD_NEW,optoken,EmitMarkup::keyword_color,newop,outvn));
dt = outvn->getTypeDefFacing();
}
else {
const Varnode *thisvn = op->getIn(1);
dt = thisvn->getType();
}
if (dt->getMetatype() == TYPE_PTR) {
dt = ((TypePointer *)dt)->getPtrTo();
}
string nm = dt->getDisplayName();
pushOp(&function_call,op);
pushAtom(Atom(nm,optoken,EmitMarkup::funcname_color,op));
// implied vn's pushed on in reverse order for efficiency
// see PrintLanguage::pushVnImplied
if (op->numInput()>3) { // Multiple (non-this) parameters
for(int4 i=2;i<op->numInput()-1;++i)
pushOp(&comma,op);
for(int4 i=op->numInput()-1;i>=2;--i)
pushVn(op->getIn(i),op,mods);
}
else if (op->numInput()==3) { // One parameter
pushVn(op->getIn(2),op,mods);
}
else { // A void function
pushAtom(Atom(EMPTY_STRING,blanktoken,EmitMarkup::no_color));
}
}
void PrintC::opReturn(const PcodeOp *op)
{
string nm;
switch(op->getHaltType()) {
default: // The most common case, plain return
// FIXME: This routine shouldn't emit directly
emit->tagOp(KEYWORD_RETURN,EmitMarkup::keyword_color,op);
if (op->numInput()>1) {
emit->spaces(1);
pushVn(op->getIn(1),op,mods);
}
return;
case PcodeOp::noreturn: // Previous instruction does not exit
case PcodeOp::halt: // Process halts
nm = "halt";
break;
case PcodeOp::badinstruction:
nm = "halt_baddata"; // CPU executes bad instruction
break;
case PcodeOp::unimplemented: // instruction is unimplemented
nm = "halt_unimplemented";
break;
case PcodeOp::missing: // Did not analyze this instruction
nm = "halt_missing";
break;
}
pushOp(&function_call,op);
pushAtom(Atom(nm,optoken,EmitMarkup::funcname_color,op));
pushAtom(Atom(EMPTY_STRING,blanktoken,EmitMarkup::no_color));
}
void PrintC::opIntZext(const PcodeOp *op,const PcodeOp *readOp)
{
if (castStrategy->isZextCast(op->getOut()->getHighTypeDefFacing(),op->getIn(0)->getHighTypeReadFacing(op))) {
if (option_hide_exts && castStrategy->isExtensionCastImplied(op,readOp))
opHiddenFunc(op);
else
opTypeCast(op);
}
else
opFunc(op);
}
void PrintC::opIntSext(const PcodeOp *op,const PcodeOp *readOp)
{
if (castStrategy->isSextCast(op->getOut()->getHighTypeDefFacing(),op->getIn(0)->getHighTypeReadFacing(op))) {
if (option_hide_exts && castStrategy->isExtensionCastImplied(op,readOp))
opHiddenFunc(op);
else
opTypeCast(op);
}
else
opFunc(op);
}
/// Print the BOOL_NEGATE but check for opportunities to flip the next operator instead
/// \param op is the BOOL_NEGATE PcodeOp
void PrintC::opBoolNegate(const PcodeOp *op)
{
if (isSet(negatetoken)) { // Check if we are negated by a previous BOOL_NEGATE
unsetMod(negatetoken); // If so, mark that negatetoken is consumed
pushVn(op->getIn(0),op,mods); // Don't print ourselves, but print our input unmodified
}
else if (checkPrintNegation(op->getIn(0))) { // If the next operator can be flipped
pushVn(op->getIn(0),op,mods|negatetoken); // Don't print ourselves, but print a modified input
}
else {
pushOp(&boolean_not,op); // Otherwise print ourselves
pushVn(op->getIn(0),op,mods); // And print our input
}
}
void PrintC::opSubpiece(const PcodeOp *op)
{
if (op->doesSpecialPrinting()) { // Special printing means it is a field extraction
const Varnode *vn = op->getIn(0);
Datatype *ct = vn->getHighTypeReadFacing(op);
if (ct->isPieceStructured()) {
int8 offset;
int8 byteOff = TypeOpSubpiece::computeByteOffsetForComposite(op);
const TypeField *field = ct->findTruncation(byteOff,op->getOut()->getSize(),op,1,offset); // Use artificial slot
if (field != (const TypeField*)0 && offset == 0) { // A formal structure field
pushOp(&object_member,op);
pushVn(vn,op,mods);
pushAtom(Atom(field->name,fieldtoken,EmitMarkup::no_color,ct,field->ident,op));
return;
}
else if (vn->isExplicit() && vn->getHigh()->getSymbolOffset() == -1) { // An explicit, entire, structured object
Symbol *sym = vn->getHigh()->getSymbol();
if (sym != (Symbol *)0) {
int4 sz = op->getOut()->getSize();
int4 off = (int4)op->getIn(1)->getOffset();
off = vn->getSpace()->isBigEndian() ? vn->getSize() - (sz + off) : off;
pushPartialSymbol(sym, off, sz, vn, op, -1);
return;
}
}
// Fall thru to functional printing
}
}
if (castStrategy->isSubpieceCast(op->getOut()->getHighTypeDefFacing(),
op->getIn(0)->getHighTypeReadFacing(op),
(uint4)op->getIn(1)->getOffset()))
opTypeCast(op);
else
opFunc(op);
}
void PrintC::opPtradd(const PcodeOp *op)
{
bool printval = isSet(print_load_value|print_store_value);
uint4 m = mods & ~(print_load_value|print_store_value);
if (printval) // Use array notation if we need value
pushOp(&subscript,op);
else // just a '+'
pushOp(&binary_plus,op);
// implied vn's pushed on in reverse order for efficiency
// see PrintLanguage::pushVnImplied
pushVn(op->getIn(1),op,m);
pushVn(op->getIn(0),op,m);
}
static bool isValueFlexible(const Varnode *vn)
{
if ((vn->isImplied())&&(vn->isWritten())) {
const PcodeOp *def = vn->getDef();
OpCode opc = def->code();
if (opc == CPUI_COPY) {
const Varnode *invn = def->getIn(0);
if (!invn->isImplied() || !invn->isWritten())
return false;
opc = invn->getDef()->code();
}
if (opc == CPUI_PTRSUB) return true;
if (opc == CPUI_PTRADD) return true;
}
return false;
}
/// We need to distinguish between the following cases:
/// - ptr-> struct spacebase or array
/// - valueoption on/off (from below)
/// - valueflex yes/no (can we turn valueoption above?)
///
/// Then the printing breaks up into the following table:
/// \code
/// val flex | val flex | val flex | val flex
/// off yes off no on yes on no
///
/// struct &( ).name &( )->name ( ).name ( )->name
/// spcbase n/a &name n/a name
/// array ( ) *( ) ( )[0] *( )[0]
/// \endcode
/// The '&' is dropped if the output type is an array
/// \param op is the PTRSUB PcodeOp
void PrintC::opPtrsub(const PcodeOp *op)
{
TypePointer *ptype;
TypePointerRel *ptrel;
Datatype *ct;
const Varnode *in0;
uintb in1const;
bool valueon,flex,arrayvalue;
uint4 m;
in0 = op->getIn(0);
in1const = op->getIn(1)->getOffset();
ptype = (TypePointer *)in0->getHighTypeReadFacing(op);
if (ptype->getMetatype() != TYPE_PTR) {
clear();
throw LowlevelError("PTRSUB off of non-pointer type");
}
if (ptype->isFormalPointerRel() && ((TypePointerRel *)ptype)->evaluateThruParent(in1const)) {
ptrel = (TypePointerRel *)ptype;
ct = ptrel->getParent();
}
else {
ptrel = (TypePointerRel *)0;
ct = ptype->getPtrTo();
}
m = mods & ~(print_load_value|print_store_value); // Current state of mods
valueon = (mods & (print_load_value|print_store_value)) != 0;
flex = isValueFlexible(in0);
if (ct->getMetatype() == TYPE_STRUCT || ct->getMetatype() == TYPE_UNION) {
int8 suboff = (int4)in1const; // How far into container
if (ptrel != (TypePointerRel *)0) {
suboff += ptrel->getPointerOffset();
suboff &= calc_mask(ptype->getSize());
if (suboff == 0) {
// Special case where we do not print a field
pushTypePointerRel(op);
if (flex)
pushVn(in0,op,m | print_load_value);
else
pushVn(in0,op,m);
return;
}
}
suboff = AddrSpace::addressToByteInt(suboff,ptype->getWordSize());
string fieldname;
Datatype *fieldtype;
int4 fieldid;
int8 newoff;
if (ct->getMetatype() == TYPE_UNION) {
if (suboff != 0)
throw LowlevelError("PTRSUB accesses union with non-zero offset");
const Funcdata *fd = op->getParent()->getFuncdata();
const ResolvedUnion *resUnion = fd->getUnionField(ptype, op, -1);
if (resUnion == (const ResolvedUnion *)0 || resUnion->getFieldNum() < 0)
throw LowlevelError("PTRSUB for union that does not resolve to a field");
const TypeField *fld = ((TypeUnion *)ct)->getField(resUnion->getFieldNum());
fieldid = fld->ident;
fieldname = fld->name;
fieldtype = fld->type;
}
else { // TYPE_STRUCT
const TypeField *fld = ct->findTruncation(suboff,0,op,0,newoff);
if (fld == (const TypeField*)0) {
if (ct->getSize() <= suboff || suboff < 0) {
clear();
throw LowlevelError("PTRSUB out of bounds into struct");
}
// Try to match the Ghidra's default field name from DataTypeComponent.getDefaultFieldName
ostringstream s;
s << "field_0x" << hex << suboff;
fieldname = s.str();
fieldtype = (Datatype*)0;
fieldid = suboff;
}
else {
fieldname = fld->name;
fieldtype = fld->type;
fieldid = fld->ident;
}
}
arrayvalue = false;
// The '&' is dropped if the output type is an array
if ((fieldtype != (Datatype *)0)&&(fieldtype->getMetatype()==TYPE_ARRAY)) {
arrayvalue = valueon; // If printing value, use [0]
valueon = true; // Don't print &
}
if (!valueon) { // Printing an ampersand
if (flex) { // EMIT &( ).name
pushOp(&addressof,op);
pushOp(&object_member,op);
if (ptrel != (TypePointerRel *)0)
pushTypePointerRel(op);
pushVn(in0,op,m | print_load_value);
pushAtom(Atom(fieldname,fieldtoken,EmitMarkup::no_color,ct,fieldid,op));
}
else { // EMIT &( )->name