-
Notifications
You must be signed in to change notification settings - Fork 49
/
ifacedecomp.cc
3665 lines (3147 loc) · 117 KB
/
ifacedecomp.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 "ifacedecomp.hh"
extern "C" {
#include <time.h>
}
#include "pcodeparse.hh"
#include "blockaction.hh"
namespace ghidra {
// Constructing this registers the capability
IfaceDecompCapability IfaceDecompCapability::ifaceDecompCapability;
IfaceDecompCapability::IfaceDecompCapability(void)
{
name = "decomp";
}
void IfaceDecompCapability::registerCommands(IfaceStatus *status)
{
status->registerCom(new IfcComment(),"//"); //Note: A space must follow this when used.
status->registerCom(new IfcComment(),"#"); //Note: A space must follow this when used.
status->registerCom(new IfcComment(),"%"); //Note: A space must follow this when used.
status->registerCom(new IfcQuit(),"quit");
status->registerCom(new IfcHistory(),"history");
status->registerCom(new IfcOpenfile(),"openfile", "write");
status->registerCom(new IfcOpenfileAppend(),"openfile","append");
status->registerCom(new IfcClosefile(),"closefile");
status->registerCom(new IfcEcho(),"echo");
status->registerCom(new IfcSource(),"source");
status->registerCom(new IfcOption(),"option");
status->registerCom(new IfcParseFile(),"parse","file");
status->registerCom(new IfcParseLine(),"parse","line");
status->registerCom(new IfcAdjustVma(),"adjust","vma");
status->registerCom(new IfcFuncload(),"load","function");
status->registerCom(new IfcAddrrangeLoad(),"load","addr");
status->registerCom(new IfcReadSymbols(),"read","symbols");
status->registerCom(new IfcCleararch(),"clear","architecture");
status->registerCom(new IfcMapaddress(),"map","address");
status->registerCom(new IfcMaphash(),"map","hash");
status->registerCom(new IfcMapParam(),"map","param");
status->registerCom(new IfcMapReturn(),"map","return");
status->registerCom(new IfcMapfunction(),"map","function");
status->registerCom(new IfcMapexternalref(),"map","externalref");
status->registerCom(new IfcMaplabel(),"map","label");
status->registerCom(new IfcMapconvert(),"map","convert");
status->registerCom(new IfcMapunionfacet(), "map", "unionfacet");
status->registerCom(new IfcPrintdisasm(),"disassemble");
status->registerCom(new IfcDecompile(),"decompile");
status->registerCom(new IfcDump(),"dump");
status->registerCom(new IfcDumpbinary(),"binary");
status->registerCom(new IfcForcegoto(),"force","goto");
status->registerCom(new IfcForceFormat(),"force","varnode");
status->registerCom(new IfcForceDatatypeFormat(),"force","datatype");
status->registerCom(new IfcProtooverride(),"override","prototype");
status->registerCom(new IfcJumpOverride(),"override","jumptable");
status->registerCom(new IfcFlowOverride(),"override","flow");
status->registerCom(new IfcDeadcodedelay(),"deadcode","delay");
status->registerCom(new IfcGlobalAdd(),"global","add");
status->registerCom(new IfcGlobalRemove(),"global","remove");
status->registerCom(new IfcGlobalify(),"global","spaces");
status->registerCom(new IfcGlobalRegisters(),"global","registers");
status->registerCom(new IfcGraphDataflow(),"graph","dataflow");
status->registerCom(new IfcGraphControlflow(),"graph","controlflow");
status->registerCom(new IfcGraphDom(),"graph","dom");
status->registerCom(new IfcPrintLanguage(),"print","language");
status->registerCom(new IfcPrintCStruct(),"print","C");
status->registerCom(new IfcPrintCFlat(),"print","C","flat");
status->registerCom(new IfcPrintCGlobals(),"print","C","globals");
status->registerCom(new IfcPrintCTypes(),"print","C","types");
status->registerCom(new IfcPrintCXml(),"print","C","xml");
status->registerCom(new IfcPrintParamMeasures(),"print","parammeasures");
status->registerCom(new IfcProduceC(),"produce","C");
status->registerCom(new IfcProducePrototypes(),"produce","prototypes");
status->registerCom(new IfcPrintRaw(),"print","raw");
status->registerCom(new IfcPrintInputs(),"print","inputs");
status->registerCom(new IfcPrintInputsAll(),"print","inputs","all");
status->registerCom(new IfcListaction(),"list","action");
status->registerCom(new IfcListOverride(),"list","override");
status->registerCom(new IfcListprototypes(),"list","prototypes");
status->registerCom(new IfcSetcontextrange(),"set","context");
status->registerCom(new IfcSettrackedrange(),"set","track");
status->registerCom(new IfcBreakstart(),"break","start");
status->registerCom(new IfcBreakaction(),"break","action");
status->registerCom(new IfcPrintSpaces(),"print","spaces");
status->registerCom(new IfcPrintHigh(),"print","high");
status->registerCom(new IfcPrintTree(),"print","tree","varnode");
status->registerCom(new IfcPrintBlocktree(),"print","tree","block");
status->registerCom(new IfcPrintLocalrange(),"print","localrange");
status->registerCom(new IfcPrintMap(),"print","map");
status->registerCom(new IfcPrintVarnode(),"print","varnode");
status->registerCom(new IfcPrintCover(),"print","cover","high");
status->registerCom(new IfcVarnodeCover(),"print","cover","varnode");
status->registerCom(new IfcVarnodehighCover(),"print","cover","varnodehigh");
status->registerCom(new IfcPrintExtrapop(),"print","extrapop");
status->registerCom(new IfcPrintActionstats(),"print","actionstats");
status->registerCom(new IfcResetActionstats(),"reset","actionstats");
status->registerCom(new IfcCountPcode(),"count","pcode");
status->registerCom(new IfcTypeVarnode(),"type","varnode");
status->registerCom(new IfcNameVarnode(),"name","varnode");
status->registerCom(new IfcRename(),"rename");
status->registerCom(new IfcRetype(),"retype");
status->registerCom(new IfcRemove(),"remove");
status->registerCom(new IfcIsolate(),"isolate");
status->registerCom(new IfcLockPrototype(),"prototype","lock");
status->registerCom(new IfcUnlockPrototype(),"prototype","unlock");
status->registerCom(new IfcCommentInstr(),"comment","instruction");
status->registerCom(new IfcDuplicateHash(),"duplicate","hash");
status->registerCom(new IfcCallGraphBuild(),"callgraph","build");
status->registerCom(new IfcCallGraphBuildQuick(),"callgraph","build","quick");
status->registerCom(new IfcCallGraphDump(),"callgraph","dump");
status->registerCom(new IfcCallGraphLoad(),"callgraph","load");
status->registerCom(new IfcCallGraphList(),"callgraph","list");
status->registerCom(new IfcCallFixup(),"fixup","call");
status->registerCom(new IfcCallOtherFixup(),"fixup","callother");
status->registerCom(new IfcFixupApply(),"fixup","apply");
status->registerCom(new IfcVolatile(),"volatile");
status->registerCom(new IfcReadonly(),"readonly");
status->registerCom(new IfcPointerSetting(),"pointer","setting");
status->registerCom(new IfcPreferSplit(),"prefersplit");
status->registerCom(new IfcStructureBlocks(),"structure","blocks");
status->registerCom(new IfcAnalyzeRange(), "analyze","range");
status->registerCom(new IfcLoadTestFile(), "load","test","file");
status->registerCom(new IfcListTestCommands(), "list","test","commands");
status->registerCom(new IfcExecuteTestCommand(), "execute","test","command");
#ifdef CPUI_RULECOMPILE
status->registerCom(new IfcParseRule(),"parse","rule");
status->registerCom(new IfcExperimentalRules(),"experimental","rules");
#endif
status->registerCom(new IfcContinue(),"continue");
#ifdef OPACTION_DEBUG
status->registerCom(new IfcDebugAction(),"debug","action");
status->registerCom(new IfcTraceBreak(),"trace","break");
status->registerCom(new IfcTraceAddress(),"trace","address");
status->registerCom(new IfcTraceEnable(),"trace","enable");
status->registerCom(new IfcTraceDisable(),"trace","disable");
status->registerCom(new IfcTraceClear(),"trace","clear");
status->registerCom(new IfcTraceList(),"trace","list");
status->registerCom(new IfcBreakjump(),"break","jumptable");
#endif
}
/// Runs over every function in the scope, or any sub-scope , calling
/// iterationCallback()
/// \param scope is the given scope
void IfaceDecompCommand::iterateScopesRecursive(Scope *scope)
{
if (!scope->isGlobal()) return;
iterateFunctionsAddrOrder(scope);
ScopeMap::const_iterator iter,enditer;
iter = scope->childrenBegin();
enditer = scope->childrenEnd();
for(;iter!=enditer;++iter) {
iterateScopesRecursive((*iter).second);
}
}
/// Runs over every function in the scope calling iterationCallback().
/// \param scope is the given scope
void IfaceDecompCommand::iterateFunctionsAddrOrder(Scope *scope)
{
MapIterator miter,menditer;
miter = scope->begin();
menditer = scope->end();
while(miter != menditer) {
Symbol *sym = (*miter)->getSymbol();
FunctionSymbol *fsym = dynamic_cast<FunctionSymbol *>(sym);
++miter;
if (fsym != (FunctionSymbol *)0)
iterationCallback(fsym->getFunction());
}
}
/// Scopes are traversed depth-first, then within a scope, functions are
/// traversed in address order.
void IfaceDecompCommand::iterateFunctionsAddrOrder(void)
{
if (dcp->conf == (Architecture *)0)
throw IfaceExecutionError("No architecture loaded");
iterateScopesRecursive(dcp->conf->symboltab->getGlobalScope());
}
/// Traversal is based on the current CallGraph for the program.
/// Child functions are traversed before their parents.
void IfaceDecompCommand::iterateFunctionsLeafOrder(void)
{
if (dcp->conf == (Architecture *)0)
throw IfaceExecutionError("No architecture loaded");
if (dcp->cgraph == (CallGraph *)0)
throw IfaceExecutionError("No callgraph present");
CallGraphNode *node;
node = dcp->cgraph->initLeafWalk();
while(node != (CallGraphNode *)0) {
if (node->getName().size()==0) continue; // Skip if has no name
Funcdata *fd = node->getFuncdata();
if (fd != (Funcdata *)0)
iterationCallback(fd);
node = dcp->cgraph->nextLeaf(node);
}
}
IfaceDecompData::IfaceDecompData(void)
{
conf = (Architecture *)0;
fd = (Funcdata *)0;
cgraph = (CallGraph *)0;
testCollection = (FunctionTestCollection *)0;
#ifdef OPACTION_DEBUG
jumptabledebug = false;
#endif
}
IfaceDecompData::~IfaceDecompData(void)
{
if (cgraph != (CallGraph *)0)
delete cgraph;
if (conf != (Architecture *)0)
delete conf;
if (testCollection != (FunctionTestCollection *)0)
delete testCollection;
// fd will get deleted with Database
}
void IfaceDecompData::allocateCallGraph(void)
{
if (cgraph != (CallGraph *)0)
delete cgraph;
cgraph = new CallGraph(conf);
}
/// This is called if a command throws a low-level error.
/// It clears any analysis on the function, sets the current function
/// to null, and issues a warning.
/// \param s is the stream to write the warning to
void IfaceDecompData::abortFunction(ostream &s)
{
if (fd == (Funcdata *)0) return;
s << "Unable to proceed with function: " << fd->getName() << endl;
conf->clearAnalysis(fd);
fd = (Funcdata *)0;
}
void IfaceDecompData::clearArchitecture(void)
{
if (conf != (Architecture *)0)
delete conf;
conf = (Architecture *)0;
fd = (Funcdata *)0;
}
/// \class IfcComment
/// \brief A comment within a command script: `% A comment in a script`
///
/// This commands does nothing but attaches to comment tokens like:
/// - \#
/// - %
/// - //
///
/// allowing comment lines in a script file
void IfcComment::execute(istream &s)
{
//Do nothing
}
/// \class IfcOption
/// \brief Adjust a decompiler option: `option <optionname> [<param1>] [<param2>] [<param3>]`
///
/// Passes command-line parameters to an ArchOption object registered with
/// the current architecture's OptionDatabase. Options are looked up by name
/// and can be configure with up to 3 parameters. Options generally report success
/// or failure back to the console.
void IfcOption::execute(istream &s)
{
string optname;
string p1,p2,p3;
if (dcp->conf == (Architecture *)0)
throw IfaceExecutionError("No load image present");
s >> ws >> optname >> ws;
if (optname.size()==0)
throw IfaceParseError("Missing option name");
if (!s.eof()) {
s >> p1 >> ws;
if (!s.eof()) {
s >> p2 >> ws;
if (!s.eof()) {
s >> p3 >> ws;
if (!s.eof())
throw IfaceParseError("Too many option parameters");
}
}
}
try {
string res = dcp->conf->options->set(ElementId::find(optname,0),p1,p2,p3);
*status->optr << res << endl;
}
catch(ParseError &err) {
*status->optr << err.explain << endl;
throw IfaceParseError("Bad option");
}
catch(RecovError &err) {
*status->optr << err.explain << endl;
throw IfaceExecutionError("Bad option");
}
}
/// \class IfcParseFile
/// \brief Parse a file with C declarations: `parse file <filename>`
///
/// The file must contain C syntax data-type and function declarations.
/// Data-types become part of the program, and function declarations,
/// if the symbol already exists, associate the prototype with the symbol.
void IfcParseFile::execute(istream &s)
{
if (dcp->conf == (Architecture *)0)
throw IfaceExecutionError("No load image present");
string filename;
ifstream fs;
s >> ws >> filename;
if (filename.empty())
throw IfaceParseError("Missing filename");
fs.open( filename.c_str() );
if (!fs)
throw IfaceExecutionError("Unable to open file: "+filename);
try { // Try to parse the file
parse_C(dcp->conf,fs);
}
catch(ParseError &err) {
*status->optr << "Error in C syntax: " << err.explain << endl;
throw IfaceExecutionError("Bad C syntax");
}
fs.close();
}
/// \class IfcParseLine
/// \brief Parse a line of C syntax: `parse line ...`
///
/// The line can contain a declaration either a data-type or a function prototype:
/// - `parse line typedef int4 *specialint;`
/// - `parse line struct mystruct { int4 a; int4 b; }`
/// - `parse line extern void myfunc(int4 a,int4 b);`
///
/// Data-types go straight into the program. For a prototype, the function symbol
/// must already exist.
void IfcParseLine::execute(istream &s)
{
if (dcp->conf == (Architecture *)0)
throw IfaceExecutionError("No load image present");
s >> ws;
if (s.eof())
throw IfaceParseError("No input");
try { // Try to parse the line
parse_C(dcp->conf,s);
}
catch(ParseError &err) {
*status->optr << "Error in C syntax: " << err.explain << endl;
throw IfaceExecutionError("Bad C syntax");
}
}
/// \class IfcAdjustVma
/// \brief Change the base address of the load image: `adjust vma 0xabcd0123`
///
/// The provided parameter is added to the current base address of the image.
/// This only affects the address of bytes in the image and so should be done
/// before functions and other symbols are layed down.
void IfcAdjustVma::execute(istream &s)
{
unsigned long adjust;
adjust = 0uL;
if (dcp->conf == (Architecture *)0)
throw IfaceExecutionError("No load image present");
s.unsetf(ios::dec | ios::hex | ios::oct); // Let user specify base
s >> ws >> adjust;
if (adjust == 0uL)
throw IfaceParseError("No adjustment parameter");
dcp->conf->loader->adjustVma(adjust);
}
#ifdef OPACTION_DEBUG
static void jump_callback(Funcdata &orig,Funcdata &fd);
#endif
/// \brief Generate raw p-code for the current function
///
/// Follow flow from the entry point of the function and generate the
/// raw p-code ops for all instructions, up to \e return instructions.
/// If a \e size in bytes is provided, it bounds the memory region where flow
/// can be followed. Otherwise, a zero \e size allows unbounded flow tracing.
/// \param s is a output stream for reporting function details or errors
/// \param size (if non-zero) is the maximum number of bytes to disassemble
void IfaceDecompData::followFlow(ostream &s,int4 size)
{
#ifdef OPACTION_DEBUG
if (jumptabledebug)
fd->enableJTCallback(jump_callback);
#endif
try {
if (size==0) {
Address baddr(fd->getAddress().getSpace(),0);
Address eaddr(fd->getAddress().getSpace(),fd->getAddress().getSpace()->getHighest());
fd->followFlow(baddr,eaddr);
}
else
fd->followFlow(fd->getAddress(),fd->getAddress()+size);
s << "Function " << fd->getName() << ": ";
fd->getAddress().printRaw(s);
s << endl;
} catch(RecovError &err) {
s << "Function " << fd->getName() << ": " << err.explain << endl;
}
}
/// \class IfcFuncload
/// \brief Make a specific function current: `load function <functionname>`
///
/// The name must be a fully qualified symbol with "::" separating namespaces.
/// If the symbol represents a function, that function becomes \e current for
/// the console. If there are bytes for the function, raw p-code and control-flow
/// are calculated.
void IfcFuncload::execute(istream &s)
{
string funcname;
Address offset;
s >> funcname;
if (dcp->conf == (Architecture *)0)
throw IfaceExecutionError("No image loaded");
string basename;
Scope *funcscope = dcp->conf->symboltab->resolveScopeFromSymbolName(funcname,"::",basename,(Scope *)0);
if (funcscope == (Scope *)0)
throw IfaceExecutionError("Bad namespace: "+funcname);
dcp->fd = funcscope->queryFunction( basename ); // Is function already in database
if (dcp->fd == (Funcdata *)0)
throw IfaceExecutionError("Unknown function name: "+funcname);
if (!dcp->fd->hasNoCode())
dcp->followFlow(*status->optr,0);
}
/// \class IfcAddrrangeLoad
/// \brief Create a new function at an address: `load addr <address> [<funcname>]`
///
/// A new function is created at the provided address. If a name is provided, this
/// becomes the function symbol, otherwise a default name is generated.
/// The function becomes \e current for the interface, and if bytes are present,
/// raw p-code and control-flow are generated.
void IfcAddrrangeLoad::execute(istream &s)
{
int4 size;
string name;
Address offset=parse_machaddr(s,size,*dcp->conf->types); // Read required address
s >> ws;
if (size <= offset.getAddrSize()) // Was a real size specified
size = 0;
if (dcp->conf->loader == (LoadImage *)0)
throw IfaceExecutionError("No binary loaded");
s >> name; // Read optional name
if (name.empty())
dcp->conf->nameFunction(offset,name); // Pick default name if necessary
dcp->fd = dcp->conf->symboltab->getGlobalScope()->addFunction( offset,name)->getFunction();
dcp->followFlow(*status->optr,size);
}
/// \class IfcCleararch
/// \brief Clear the current architecture/program: `clear architecture`
void IfcCleararch::execute(istream &s)
{
dcp->clearArchitecture();
}
/// \class IfcReadSymbols
/// \brief Read in symbols from the load image: `read symbols`
///
/// If the load image format encodes symbol information. These are
/// read in and attached to the appropriate address.
void IfcReadSymbols::execute(istream &s)
{
if (dcp->conf == (Architecture *)0)
throw IfaceExecutionError("No load image present");
if (dcp->conf->loader == (LoadImage *)0)
throw IfaceExecutionError("No binary loaded");
dcp->conf->readLoaderSymbols("::");
}
/// \class IfcMapaddress
/// \brief Map a new symbol into the program: `map address <address> <typedeclaration>`
///
/// Create a new variable in the current scope
/// \code
/// map address r0x1000 int4 globalvar
/// \endcode
/// The symbol specified in the type declaration can qualify the namespace using the "::"
/// specifier. If there is a current function, the variable is local to the function.
/// Otherwise the symbol is created relative to the global scope.
void IfcMapaddress::execute(istream &s)
{
Datatype *ct;
string name;
int4 size;
Address addr = parse_machaddr(s,size,*dcp->conf->types); // Read required address;
s >> ws;
ct = parse_type(s,name,dcp->conf); // Parse the required type
if (dcp->fd != (Funcdata *)0) {
Symbol *sym;
sym = dcp->fd->getScopeLocal()->addSymbol(name,ct,addr,Address())->getSymbol();
sym->getScope()->setAttribute(sym,Varnode::namelock|Varnode::typelock);
}
else {
Symbol *sym;
uint4 flags = Varnode::namelock|Varnode::typelock;
flags |= dcp->conf->symboltab->getProperty(addr); // Inherit existing properties
string basename;
Scope *scope = dcp->conf->symboltab->findCreateScopeFromSymbolName(name, "::", basename, (Scope *)0);
sym = scope->addSymbol(basename,ct,addr,Address())->getSymbol();
sym->getScope()->setAttribute(sym,flags);
if (scope->getParent() != (Scope *)0) { // If this is a global namespace scope
SymbolEntry *e = sym->getFirstWholeMap(); // Adjust range
dcp->conf->symboltab->addRange(scope,e->getAddr().getSpace(),e->getFirst(),e->getLast());
}
}
}
/// \class IfcMaphash
/// \brief Add a dynamic symbol to the current function: `map hash <address> <hash> <typedeclaration>`
///
/// The command only creates local variables for the current function.
/// The name and data-type are taken from a C syntax type declaration. The symbol is
/// not associated with a particular storage address but with a specific Varnode in the data-flow,
/// specified by a code address and hash of the local data-flow structure.
void IfcMaphash::execute(istream &s)
{
if (dcp->fd == (Funcdata *)0)
throw IfaceExecutionError("No function loaded");
Datatype *ct;
string name;
uint8 hash;
int4 size;
Address addr = parse_machaddr(s,size,*dcp->conf->types); // Read pc address of hash
s >> hex >> hash; // Parse the hash value
s >> ws;
ct = parse_type(s,name,dcp->conf); // Parse the required type and name
Symbol *sym = dcp->fd->getScopeLocal()->addDynamicSymbol(name,ct,addr,hash);
sym->getScope()->setAttribute(sym,Varnode::namelock|Varnode::typelock);
}
/// \class IfcMapParam
/// \brief Map a parameter symbol for the current function: `map param #i <address> <typedeclaration>`
///
/// The position of the parameter in the input list is parsed as an integer, starting at 0.
/// The address range used for parameter is explicitly set. The data-type and name of the parameter
/// are parsed from the type declaration. The parameter is treated as name and type locked.
void IfcMapParam::execute(istream &s)
{
if (dcp->fd == (Funcdata *)0)
throw IfaceExecutionError("No function loaded");
int4 i;
string name;
int4 size;
ParameterPieces piece;
s >> dec >> i; // Position of the parameter
piece.addr = parse_machaddr(s,size,*dcp->conf->types); // Starting address of parameter
piece.type = parse_type(s,name,dcp->conf);
piece.flags = ParameterPieces::typelock | ParameterPieces::namelock;
dcp->fd->getFuncProto().setParam(i, name, piece);
}
/// \class IfcMapReturn
/// \brief Map the return storage for the current function: `map return <address> <typedeclaration>`
///
/// The address range used for return storage is explicitly set, and the return value is set to the
/// parsed data-type. The function's output is considered locked.
void IfcMapReturn::execute(istream &s)
{
if (dcp->fd == (Funcdata *)0)
throw IfaceExecutionError("No function loaded");
string name;
int4 size;
ParameterPieces piece;
piece.addr = parse_machaddr(s,size,*dcp->conf->types); // Starting address of return storage
piece.type = parse_type(s,name,dcp->conf);
piece.flags = ParameterPieces::typelock;
dcp->fd->getFuncProto().setOutput(piece);
}
/// \class IfcMapfunction
/// \brief Create a new function: `map function <address> [<functionname>] [nocode]`
///
/// Create a new function symbol at the provided address.
/// A symbol name can be provided, otherwise a default name is selected.
/// The new function becomes \e current for the console.
/// The provided address gives the entry point for the function. Unless the final keyword
/// "nocode" is provided, the underlying bytes in the load image are used for any
/// future disassembly or decompilation.
void IfcMapfunction::execute(istream &s)
{
string name;
int4 size;
if ((dcp->conf == (Architecture *)0)||(dcp->conf->loader == (LoadImage *)0))
throw IfaceExecutionError("No binary loaded");
Address addr = parse_machaddr(s,size,*dcp->conf->types); // Read required address;
s >> name; // Read optional name
if (name.empty())
dcp->conf->nameFunction(addr,name); // Pick default name if necessary
string basename;
Scope *scope = dcp->conf->symboltab->findCreateScopeFromSymbolName(name, "::", basename, (Scope *)0);
dcp->fd = scope->addFunction(addr,name)->getFunction();
string nocode;
s >> ws >> nocode;
if (nocode == "nocode")
dcp->fd->setNoCode(true);
}
/// \class IfcMapexternalref
/// \brief Create an external ref symbol `map externalref <address> <refaddress> [<name>]`
///
/// Creates a symbol for a function pointer and associates a specific address as
/// a value for that symbol. The first address specified is the address of the symbol,
/// The second address is the address referred to by the pointer. Indirect calls
/// through the function pointer will be converted to direct calls to the referred address.
/// A symbol name can be provided, otherwise a default one is generated.
void IfcMapexternalref::execute(istream &s)
{
int4 size1,size2;
Address addr1 = parse_machaddr(s,size1,*dcp->conf->types); // Read externalref address
Address addr2 = parse_machaddr(s,size2,*dcp->conf->types); // Read referred to address
string name;
s >> name; // Read optional name
dcp->conf->symboltab->getGlobalScope()->addExternalRef(addr1,addr2,name);
}
/// \class IfcMaplabel
/// \brief Create a code label: `map label <name> <address>`
///
/// Label a specific code address. This creates a LabSymbol which is usually
/// an internal control-flow target. The symbol is local to the \e current function
/// if it exists, otherwise the symbol is added to the global scope.
void IfcMaplabel::execute(istream &s)
{
string name;
s >> name;
if (name.size()==0)
throw IfaceParseError("Need label name and address");
int4 size;
Address addr = parse_machaddr(s,size,*dcp->conf->types); // Read address
Scope *scope;
if (dcp->fd != (Funcdata *)0)
scope = dcp->fd->getScopeLocal();
else
scope = dcp->conf->symboltab->getGlobalScope();
Symbol *sym = scope->addCodeLabel(addr,name);
scope->setAttribute(sym,Varnode::namelock|Varnode::typelock);
}
/// \class IfcMapconvert
/// \brief Create an convert directive: `map convert <format> <value> <address> <hash>`
///
/// Creates a \e convert directive that causes a targeted constant value to be displayed
/// with the specified integer format. The constant is specified by \e value, and the
/// \e address of the p-code op using the constant plus a dynamic \e hash is also given.
void IfcMapconvert::execute(istream &s)
{
if (dcp->fd == (Funcdata *)0)
throw IfaceExecutionError("No function loaded");
string name;
uintb value;
uint8 hash;
int4 size;
uint4 format = 0;
s >> name; // Parse the format token
if (name == "hex")
format = Symbol::force_hex;
else if (name == "dec")
format = Symbol::force_dec;
else if (name == "bin")
format = Symbol::force_bin;
else if (name == "oct")
format = Symbol::force_oct;
else if (name == "char")
format = Symbol::force_char;
else
throw IfaceParseError("Bad convert format");
s >> ws >> hex >> value;
Address addr = parse_machaddr(s,size,*dcp->conf->types); // Read pc address of hash
s >> hex >> hash; // Parse the hash value
dcp->fd->getScopeLocal()->addEquateSymbol("", format, value, addr, hash);
}
/// \class IfcMapunionfacet
/// \brief Create a union field forcing directive: `map facet <union> <fieldnum> <address> <hash>`
///
/// Creates a \e facet directive that associates a given field of a \e union data-type with
/// a varnode in the context of a specific p-code op accessing it. The varnode and p-code op
/// are specified by dynamic hash.
void IfcMapunionfacet::execute(istream &s)
{
Datatype *ct;
string unionName;
int4 fieldNum;
int4 size;
uint8 hash;
if (dcp->fd == (Funcdata *)0)
throw IfaceExecutionError("No function loaded");
s >> ws >> unionName;
ct = dcp->conf->types->findByName(unionName);
if (ct == (Datatype *)0 || ct->getMetatype() != TYPE_UNION)
throw IfaceParseError("Bad union data-type: " + unionName);
s >> ws >> dec >> fieldNum;
if (fieldNum < -1 || fieldNum >= ct->numDepend())
throw IfaceParseError("Bad field index");
Address addr = parse_machaddr(s,size,*dcp->conf->types); // Read pc address of hash
s >> hex >> hash; // Parse the hash value
ostringstream s2;
s2 << "unionfacet" << dec << (fieldNum + 1) << '_' << hex << addr.getOffset();
Symbol *sym = dcp->fd->getScopeLocal()->addUnionFacetSymbol(s2.str(), ct, fieldNum, addr, hash);
dcp->fd->getScopeLocal()->setAttribute(sym, Varnode::typelock | Varnode::namelock);
}
/// \class IfcPrintdisasm
/// \brief Print disassembly of a memory range: `disassemble [<address1> <address2>]`
///
/// If no addresses are provided, disassembly for the current function is displayed.
/// Otherwise disassembly is between the two provided addresses.
void IfcPrintdisasm::execute(istream &s)
{
Architecture *glb;
Address addr;
int4 size;
// TODO add partial listings
s >> ws;
if (s.eof()) {
if (dcp->fd == (Funcdata *)0)
throw IfaceExecutionError("No function selected");
*status->fileoptr << "Assembly listing for " << dcp->fd->getName() << endl;
addr = dcp->fd->getAddress();
size = dcp->fd->getSize();
glb = dcp->fd->getArch();
}
else {
addr = parse_machaddr(s,size,*dcp->conf->types); // Read beginning address
s >> ws;
Address offset2=parse_machaddr(s,size,*dcp->conf->types);
size = offset2.getOffset() - addr.getOffset();
glb = dcp->conf;
}
IfaceAssemblyEmit assem(status->fileoptr,10);
while(size > 0) {
int4 sz;
sz = glb->translate->printAssembly(assem,addr);
addr = addr + sz;
size -= sz;
}
}
/// \class IfcDump
/// \brief Display bytes in the load image: `dump <address+size>`
///
/// The command does a hex listing of the specific memory region.
void IfcDump::execute(istream &s)
{
int4 size;
uint1 *buffer;
Address offset = parse_machaddr(s,size,*dcp->conf->types);
buffer = dcp->conf->loader->load(size,offset);
print_data(*status->fileoptr,buffer,size,offset);
delete [] buffer;
}
/// \class IfcDumpbinary
/// \brief Dump a memory to file: `binary <address+size> <filename>`
///
/// Raw bytes from the specified memory region in the load image are written
/// to a file.
void IfcDumpbinary::execute(istream &s)
{
int4 size;
uint1 *buffer;
Address offset = parse_machaddr(s,size,*dcp->conf->types);
string filename;
s >> ws;
if (s.eof())
throw IfaceParseError("Missing file name for binary dump");
s >> filename;
ofstream os;
os.open(filename.c_str());
if (!os)
throw IfaceExecutionError("Unable to open file "+filename);
buffer = dcp->conf->loader->load(size,offset);
os.write((const char *)buffer,size);
delete [] buffer;
os.close();
}
/// \class IfcDecompile
/// \brief Decompile the current function: `decompile`
///
/// Decompilation is started for the current function. Any previous decompilation
/// analysis on the function is cleared first. The process respects
/// any active break points or traces, so decompilation may not complete.
void IfcDecompile::execute(istream &s)
{
int4 res;
if (dcp->fd == (Funcdata *)0)
throw IfaceExecutionError("No function selected");
if (dcp->fd->hasNoCode()) {
*status->optr << "No code for " << dcp->fd->getName() << endl;
return;
}
if (dcp->fd->isProcStarted()) { // Free up old decompile
*status->optr << "Clearing old decompilation" << endl;
dcp->conf->clearAnalysis(dcp->fd);
}
*status->optr << "Decompiling " << dcp->fd->getName() << endl;
dcp->conf->allacts.getCurrent()->reset(*dcp->fd);
res = dcp->conf->allacts.getCurrent()->perform( *dcp->fd );
if (res<0) {
*status->optr << "Break at ";
dcp->conf->allacts.getCurrent()->printState(*status->optr);
}
else {
*status->optr << "Decompilation complete";
if (res==0)
*status->optr << " (no change)";
}
*status->optr << endl;
}
/// \class IfcPrintCFlat
/// \brief Print current function without control-flow: `print C flat`
void IfcPrintCFlat::execute(istream &s)
{
if (dcp->fd == (Funcdata *)0)
throw IfaceExecutionError("No function selected");
dcp->conf->print->setOutputStream(status->fileoptr);
dcp->conf->print->setFlat(true);
dcp->conf->print->docFunction(dcp->fd);
dcp->conf->print->setFlat(false);
}
/// \class IfcPrintCGlobals
/// \brief Print declarations for any known global variables: `print C globals`
void IfcPrintCGlobals::execute(istream &s)
{
if (dcp->conf == (Architecture *)0)
throw IfaceExecutionError("No load image present");
dcp->conf->print->setOutputStream(status->fileoptr);
dcp->conf->print->docAllGlobals();
}
/// \class IfcPrintCTypes
/// \brief Print any known type definitions: `print C types`
void IfcPrintCTypes::execute(istream &s)
{
if (dcp->conf == (Architecture *)0)
throw IfaceExecutionError("No load image present");
if (dcp->conf->types != (TypeFactory *)0) {
dcp->conf->print->setOutputStream(status->fileoptr);
dcp->conf->print->docTypeDefinitions(dcp->conf->types);
}
}
/// \class IfcPrintCXml
/// \brief Print the current function with C syntax and XML markup:`print C xml`
void IfcPrintCXml::execute(istream &s)
{
if (dcp->fd == (Funcdata *)0)
throw IfaceExecutionError("No function selected");
dcp->conf->print->setOutputStream(status->fileoptr);
dcp->conf->print->setMarkup(true);
dcp->conf->print->setPackedOutput(false);
dcp->conf->print->docFunction(dcp->fd);
*status->fileoptr << endl;
dcp->conf->print->setMarkup(false);
}
/// \class IfcPrintCStruct
/// \brief Print the current function using C syntax:`print C`
void IfcPrintCStruct::execute(istream &s)
{
if (dcp->fd == (Funcdata *)0)
throw IfaceExecutionError("No function selected");
dcp->conf->print->setOutputStream(status->fileoptr);
dcp->conf->print->docFunction(dcp->fd);
}
/// \class IfcPrintLanguage
/// \brief Print current output using a specific language: `print language <langname>`
///
/// The current function must already be decompiled.
void IfcPrintLanguage::execute(istream &s)
{
if (dcp->fd == (Funcdata *)0)
throw IfaceExecutionError("No function selected");
s >> ws;
if (s.eof())
throw IfaceParseError("No print language specified");
string langroot;
s >> langroot;
langroot = langroot + "-language";