-
Notifications
You must be signed in to change notification settings - Fork 5
/
driver.cc
2042 lines (1812 loc) · 76.4 KB
/
driver.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
/*
* Copyright (C) 1996-2001, The University of Queensland
* Copyright (C) 2000-2001, Sun Microsystems, Inc
*
* See the file "LICENSE.TERMS" for information on usage and
* redistribution of this file, and for a DISCLAIMER OF ALL
* WARRANTIES.
*
*/
/*==============================================================================
* FILE: driver.cc
* OVERVIEW: This file contains the command line driver for the UQBT
* binary translator framework.
*
* Copyright (C) 1996-2001, The University of Queensland, BT group
* Copyright (C) 2000-2001, Sun Microsystems, Inc
*============================================================================*/
/*
* $Revision: 1.147 $
* 2 Feb 98 - Cristina
* added routines to parse the relevant SSL file (based on -D definition of the
* architecture in use) and create the RTL dictionary. This code came
* from Doug's parse_test.cc file.
* added veryVerbose option and test to print RTL dictionary.
* 19 Feb 98 - Cristina
* loadElf() now takes a list<HRTL> to return the RTLs of the program.
* 25 Feb 98 - Cristina
* added -d option to generate .dot file from the program's CFGs.
* 11 Mar 98 - Cristina
* replaced BOOL for bool type (C++'s), same for TRUE and FALSE.
* 18 Mar 98 - Cristina
* removed call to buildCFG() as the graphs are being built while
* decoding machine instructions, as part of followControl().
* added procedure list as actual parameter to loadElf().
* 24 Mar 98 - Cristina
* removed program header variable -- obsolete.
* added program (Prog) object variable.
* replaced driver include to global.h.
* 28 Mar 98 - Cristina
* decoupled loading of the file and decoding of the machine instructions.
* changed loadElf() to return the loader object.
* 2 Jun 98 - Mike
* BinaryFile->BinaryFile
* 4 Jun 98 - Mike
* Removed the -f (follow) option
* 6 Aug 98 - Mike
* Replaced parser() with decode() (requires frontsparc.cc)
* 20 Oct 09 - Mike: Added -s switch (start at given symbol inst of main)
* 23 Oct 98 - Mike: Use RTLInstDict::readSSLFile() to read the ssl file
* 02 Nov 98 - Mike: Removed LoadRTL() (not used now)
* 10 Dec 98 - Mike: Added -f (CFG file) capability
* 15 Dec 98 - Mike: Moved decode() here from frontsparc.cc; added decodeProc()
* to remove CFG when not needed
* 19 Jan 99 - Mike: Outputs the number of procedures to the -f file now
* 05 Feb 99 - Mike: Implemented -R option (HL "rtl" display)
* 08 Feb 99 - Mike: Moved library processing from processProc() to decodeProc()
* 18 Feb 99 - Mike: Added -i option (interpreter)
* 05 Mar 99 - Mike: Write data section to cfg file
* 09 Mar 99 - Mike: Removed -i option (interpreter) ugh!
* 23 Mar 99 - Mike: Added proctrace prog option and -q
* 24 Mar 99 - Mike: Sort the BBs before -R printout
* 08 Apr 99 - Mike: removed loadElf()
* 09 Apr 99 - Mike: writeDotFile() takes the entry address now
* 20 Apr 99 - Mike: Only one entry point now; added coverage code including
* findCoverage()
* 28 Apr 99 - Doug: Moved sortBBs from wfCFG to decodeProc and renamed it to
* sortByAddress
* 28 Apr 99 - Mike: Mods for the depth first procedure decoding model
* 29 Apr 99 - Mike: Moved visit() from frontXXX()
* 03 May 99 - Mike: changed back to noback (-b has opposite sense now).
* Changes for new procedure at a time back end
* 05 May 99 - Mike: moved several blocks of code from main() to functions
* 07 May 99 - Mike: implemented -u (untidy: don't delete temp files)
* 18 May 99 - Mike: moved visit() to frontend.cc
* 28 May 99 - Mike: (started) source and dest CSR files (not complete)
* 31 May 99 - Mike: added -e switch (Endianness swaps)
* 17 Jun 99 - Mike: removed u switch; added o and m switches
* 27 Jun 99 - Doug: moved str() to util.cc
* 13 Jul 99 - Mike: -e means NO endianness (when needed) code
* 16 Sep 99 - Mike: Moved the title line, so see it if just enter "uqbtxx"
* 29 Sep 99 - Mike: Added -a (source addresses each label) option
* 18 Nov 99 - Mike: -a means NO addresses now (too useful!)
* 25 Nov 99 - Mike: Added code to generate call graph
* 13 Mar 00 - Mike: Moved SSL files to proper machine dependent directories
* 22 Mar 00 - Mike: Moved RTLDict to Prog object
* 02 Jun 00 - Mike: Support for Win32 .exe files
* 16 Jun 00 - Mike: Finally removed the cfg file option
* 19 Jul 00 - Trent: Call the back end after all analysis now
* 25 Jul 00 - Mike: Removed writeDataSections, added decodeRange(); use the
* latter to properly do speculative decoding. Also call
* prog.getTextLimits and use the results
* 17 Aug 00 - Mike: Added -L switch
* 11 Sep 00 - Mike: Don't call back end for non decoded functions (e.g. -S)
* 19 Sep 00 - Mike: proc_backend -> addSourceFile; don't translate a proc
* twice
* 8 Nov 00 - Cristina: Added support for generation of output files by use
* of the options -d, -D, -g, -G, -r and -R, which
* generate the following files: .one.dot, .dot,
* .nolib.cg.dot, .cg.dot, .rtl and .hrtl
* 09 Nov 00 - Cristina: Removed -g option
* Added support for storing rtl code in .rtl file
* 10 Nov 00 - Cristina: Added support for storing hrtl code in .hrtl file
* Separated help options into user-level and advanced
* 13 Nov 00 - Mike: Reversed sense of -y switch
* 27 Nov 00 - Mike: Added -f switch (fast but not as exact instr mapping)
* 6 Dec 00 - Brian: Merged Cristina and Mike's recent changes for big
* cvs.experimentalstuff.com merge.
* 13 Dec 00 - Mike: Replaced a few changes that were lost in the merge
* 14 Dec 00 - Brian: Added translateToJava option (for -j) to run the Java
* back end. This is false by default.
* 10 Jan 01 - Brian: Fixed a bug with "-o" writing the wrong files.
* 11 Feb 01 - Nathan: Replaced various BinaryFile invocations with magic.
* 22 Feb 01 - Nathan: Moved changeExt to util.cc
* 22 Feb 01 - Mike: Moved Loading of the binary file before the parsing of
* the SSL and PAL files (for GLOBALOFFSET)
* 26 Feb 01 - Mike: Corrected some comments confusing analyse() and analysis()
* 5 Mar 01 - Brian: Added description of "-j" flag to helpAdvanced() output.
* 20 Mar 01 - Mike: Two trivial changes
* 30 Mar 01 - Mike: Small change to name 286 SSL and PAL files
* 31 Mar 01 - Mike: getFixedDest() returns NO_ADDRESS for non fixed addresses
* 9 Apr 01 - Brian: main() now calls the JVM backend for procs that are
* speculatively decoded.
* 10 Apr 01 - Manel: Added support for Expander back end.
* 15 Apr 01 - Brian: Added support for VPO back end.
* 19 Apr 01 - Mike: Removed -a; added -l for library string
* 24 Apr 01 - Brian: Disable analysis if using VPO optimizer.
* 29 Apr 01 - Brian: Made decodeProc() recurse into children of a procedure
* if using the VPO backend.
* 06 May 01 - Mike: Don't speculatively decode functions starting with "__",
* or _fini and its children
* 09 May 01 - Mike: Flush the .hrtl stream
* 17 Jun 01 - Brian: Added support for ARM VPO back end.
* 20 Jun 01 - Jens: encapsulated main() funtionality into several functions
* in order to call it from the HRTL-Interpreter (booked in 6/Aug)
* 31 Jul 01 - Brian: New class HRTL replaces RTlist. Renamed LRTL to HRTLList.
* 01 Aug 01 - Mike: Don't create reference to VPO back end unless TGT == SPARC
* 05 Aug 01 - Brian: Corrected test for IRTL to VPO backend.
* 06 Aug 01 - Mike: Simplify conditions in HLJconds (so compare to r[0] works)
* 13 Aug 01 - Bernard: Added support for type analysis
* 21 Aug 01 - Mike: slight changes to #if for non sparc, non ARM targets
* 22 Aug 01 - Cristina: made SparcIRTLToVPOBackend references specific to
* SPARC target machine
* 30 Aug 01 - Mike: libraryParamPropagation: parameters are list (were vector)
* 24 Oct 01 - Mike: machine/pent -> machine/pentium
* 12 Dec 01 - Cristina: commented out includes and code related to VPO backends
*/
/*==============================================================================
* Dependencies.
*============================================================================*/
#include <sys/types.h> // For mkdir()
#include <sys/stat.h> // For mkdir()
#include "global.h" // global base types
#include "options.h"
#include "reg.h"
#include "ss.h"
#include "rtl.h"
#include "cfg.h"
#include "proc.h"
#include "prog.h"
#include "csr.h"
#include "frontend.h"
#include "backend.h" // Backend functions, e.g. translate2c()
#include "ElfBinaryFile.h"
#include "PalmBinaryFile.h"
#include "Win32BinaryFile.h"
#include "HpSomBinaryFile.h"
#include "outfile.h" // class OutputFile etc
#include "jvm.h" // JVM bytecode translation
#include "optimise.h" // Java optimisations
#include "expander.h" // Code expander
/* The following include files have been commented out as all VPO-related
* files have been removed from the UQBT distribution. If you are wanting
* to build a VPO backend and have obtained the license and code for VPO,
* then you should uncomment this section.
#if TGT == ARM
#include "ARMVPOBackend.h"
#elif TGT == SPARC
#include "SparcIRTLToVPOBackend.h"
#endif
*/
/*==============================================================================
* Name of machine specification files
*============================================================================*/
#if SRC == SPARC
#define SSL_NAME "machine/sparc/sparc.ssl"
#define PAL_SRC_NAME "machine/sparc/sparc.pal"
/* The following define has been commented out as all VPO-related
* files have been removed from the UQBT distribution. If you are wanting
* to build a VPO backend and have obtained the license and code for VPO,
* then you should uncomment this section.
#define SPARCVPO
*/
#elif SRC == PENT
#define SSL_NAME "machine/pentium/80386.ssl"
#define PAL_SRC_NAME "machine/pentium/386.pal"
#elif SRC == MC68K
#define SSL_NAME "machine/mc68k/mc68k.ssl"
#define PAL_SRC_NAME "machine/mc68k/mc68k.pal"
#elif SRC == W32
#define SSL_NAME "machine/pentium/80386.ssl"
#define PAL_SRC_NAME "machine/pentium/386.pal"
#elif SRC == HPPA
#define SSL_NAME "machine/hppa/hppa.ssl"
#define PAL_SRC_NAME "machine/hppa/hppa.pal"
#else
#error Must define source processor
#endif
/*==============================================================================
* Forward declarartions.
*============================================================================*/
void parseCommandLine(int argc, char**& argv, char*& inputName);
FrontEndSrc& decode(NJMCDecoder& decoder);
void dispHlRtls(UserProc* pProc, Cfg* pCfg, ofstream &of);
void error(const string& Msg);
unsigned findCoverage(const char* sSection, ElfBinaryFile* pEBF,
NJMCDecoder& decoder);
void dispCoverage(const char* inputName, NJMCDecoder& decoder);
void ensureTrailSlash(string& s);
void writeCallGraph (ofstream &ofs, string filename, BinaryFile *pBF);
bool decodeRange(ADDRESS start, ADDRESS finish, FrontEndSrc& fe, bool keep,
bool spec);
// Jens' splitting of main for interpreter
void driver_HandleArgs(int argc, char* argv[], char* &inputName);
void driver_Load(char* &inputName);
void driver_BeforeDecode(void);
void driver_Decode(void);
void driver_AfterDecode(void);
// Bernard's additional functions for type analysis
void createUseDefineDataStruct(UserProc* pProc, Cfg* pCfg);
void interProcPropagation();
void propagateBetweenBB();
void printTypeInfo();
// The following is implemented in analysis.cc
void analysis(UserProc* pProc);
/*==============================================================================
* Program globals.
*============================================================================*/
options progOptions; // Note: has a constructor below
SemTable theSemTable; // Note: must be constructed before the Prog object,
// which now contains a CSR object
Prog prog; // Program to process
/*==============================================================================
* File globals.
*============================================================================*/
static FILE* fMainDot; // .one.dot file handle
static FILE* fDot; // .dot file handle
static ofstream ofsCGDot; // .cg.dot handle
static ofstream ofRtl; // .rtl handle
static ofstream ofHrtl; // .hrtl handle
static int iDotOffset = 0; // Initial dotty file node number
static ofstream ofCfg; // Stream for writing to cfg file
static OutputFile of; // Object that takes care of assembly files
/*==============================================================================
* FUNCTION: options::options
* OVERVIEW: Constructor.
* PARAMETERS: <none>
* RETURNS: <nothing>
*============================================================================*/
options::options()
: translateToVPO(false), translateToJava(false), dot(false), allProcs(false),
verbose(false), veryVerbose(false), noback(false), useExp(false),
rtl(false), highrtl(false), trace(false), start(false), cover(false),
proctrace(true), noendian(false), make(false), singleProc(false),
callGraph(false), highLevelC(false), dynamicGlobal1(false),
noLibInMap(false), fastInstr(false), copyCode(false), bff(0), typeAnalysis(false)
{
}
/*==============================================================================
* FUNCTION: help
* OVERVIEW: Displays usage message
* PARAMETERS: thisProgram - name of the program
* RETURNS: <nothing>
*============================================================================*/
static void help (char *thisProgram)
{
printf ("Usage: %s {-<option>} binFileName\n", thisProgram);
printf("\t-D: generate .dot file for all procedures\n");
printf("\t-G: generate call Graph (.cg.dot) including library calls\n");
printf("\t-h: this Help file\n");
printf("\t-o dir: put Output files into <dir> (default is ./uqbt%c%c."
"<binFileName>)\n", SRCLETTER, TGTLETTER);
printf("\t-q: Quiet (no display of each procedure name)\n");
printf("\t-r: display RTLs as decoded (.rtl)\n");
printf("\t-R: display High Level RTLs after decoding (.hrtl)\n");
printf("\t-T: perform type analysis and output type info to a .type file\n");
printf ("\t-A: display Advanced options (useful for debugging of the translator)\n");
}
/*==============================================================================
* FUNCTION: helpAdvanced
* OVERVIEW: Displays advanced options. These options are normally
* useful for development and debugging of the translator.
* PARAMETERS: thisProgram - name of the program
* RETURNS: <nothing>
*============================================================================*/
static void helpAdvanced (char *thisProgram)
{
printf ("Usage: %s {-<switch>} binFileName\n", thisProgram);
printf("\t-b: no Backend\n");
printf("\t-Bx: use Binary file format x (e.g. h=HP PA/Risc SOM format)\n");
printf("\t-c: print Coverage of text section, no analysis or backend\n");
printf("\t-C: copy the Code section to the target binary\n");
printf("\t-d: generate .one.dot file for main or procedure selected with "
"-S\n");
printf("\t-e: don't generate Endianness swaps even if required\n");
printf("\t-Ex: use the expander backend (e.g. c=C j=JVM n=NJMCTK v=VPO)\n");
printf("\t-f: use Fast but not as exact instruction mapping\n");
printf("\t-H: emit High level C using structuring algorithms\n");
printf("\t-j: emit Java bytecodes (JVM classfiles)\n");
printf("\t-lLibString: use dollar separated list of libraries, e.g. "
"-lm$dl\n");
printf("\t-L: no Library functions in runtime address map\n");
printf("\t-m: Make the output file immediately after translation\n");
printf("\t-O: use the VPO optimizer backend\n");
printf("\t-s Symbol: use symbol instead of main as entry point\n");
printf("\t-S Symbol: as above, but only parse Single procedure\n");
printf("\t-t: print a Trace of basic blocks and procedures visited\n");
printf("\t-v: Verbose\n");
printf("\t-V: Very Verbose: detailed dump of input binary file\n");
printf("\t-y: Suppress dYnamic global processing, if there is only 1 "
"entry\n");
}
/*==============================================================================
* FUNCTION: wfCFG
* OVERVIEW: Given a non-well formed graph, transforms it into a well
* formed graph and gives the nodes their depth first orderings.
* Also compresses the CFG now (removes BBs that are only jumps)
* PARAMETERS: pCfg - the graph to be transformed
* RETURNS: <nothing>
*============================================================================*/
void wfCFG (PCFG pCfg)
{
// Create a wfCFG, sort and number the BBs
if (!pCfg->wellFormCfg()) {
error("wellFormCfg returned false"); return;
}
/* if (!pCfg->compressCfg()) {
error("compressCfg returned false"); return;
}*/
if (!pCfg->establishDFTOrder()) {
error("establishDFTOrder returned false");
return;
}
}
/*==============================================================================
* FUNCTION: getStringOption
* OVERVIEW: Get an option from the command line args. Calls help (which
* exits the program if the index requested is out of bounds.
* PARAMETERS: i - index of command line option required
* argc - the total number of command line options
* argv - the command line options
* RETURNS: the option at the given index
*============================================================================*/
char* getStringOption(int& i, int argc, char* argv[])
{
if (++i >= argc)
{
help(argv[0]);
exit(1);
}
return argv[i];
}
/*==============================================================================
* FUNCTION: main
* OVERVIEW: The entry to the program.
* PARAMETERS: argc - the total number of command line options
* argv - the command line options
* RETURNS: exit status
*============================================================================*/
int main(int argc, char *argv[]) {
char *inputName = 0; // Input binary file name
driver_HandleArgs(argc, argv, inputName);
driver_Load(inputName);
driver_BeforeDecode();
// // // // //
// D e c o d e //
// // // // //
// Decode the instuctions in this executable, starting at the
// various entry points.
NJMCDecoder decoder(prog.RTLDict, prog.csrSrc);
FrontEndSrc& fe = decode(decoder);
// // // // // // // //
// A f t e r D e c o d e //
// // // // // // // //
// Propagate type information
if (progOptions.typeAnalysis) {
// The number of times to loop is currently arbitary
for (int i = 0; i < 3; i++) {
// Propagate type information between procedures
interProcPropagation();
// Re-propagate between BBs
propagateBetweenBB();
}
}
// Close files as required
if (progOptions.dot) {
// write out dot tailer
fprintf(fMainDot, "}\n");
fclose(fMainDot);
}
if (progOptions.allProcs) {
fprintf(fDot, "}\n");
fclose(fDot);
}
// Write the call graph
if (progOptions.callGraph) {
writeCallGraph (ofsCGDot, progOptions.sCGFile, prog.pBF);
}
// Create the Expander instance if using the new expander framework
Expander *expProc;
if (progOptions.useExp) {
expProc = Expander::getExpInstance(progOptions.whExp);
if (expProc == NULL) {
ostrstream os;
os << "Non-existing expander instance <" << progOptions.whExp
<< ">\n";
error(str(os));
exit(1);
}
}
/* The following include files have been commented out as all VPO-related
* files have been removed from the UQBT distribution. If you are wanting
* to build a VPO backend and have obtained the license and code for VPO,
* then you should uncomment this section.
// if using the VPO backend, create the appropriate VPO backend instance
// BTL: this should be changed to use the Expander scheme...
#if TGT == ARM
ARMVPOBackend* vpoBackend = NULL;
#elif TGT == SPARC
SparcIRTLToVPOBackend* vpoBackend = NULL;
#endif
if (progOptions.translateToVPO) {
#if TGT == ARM
vpoBackend = new ARMVPOBackend(prog);
#elif TGT == SPARC
vpoBackend = new SparcIRTLToVPOBackend(prog);
#endif
}
*/
// Call the backend to generate everything needed
PROGMAP::const_iterator it;
Proc* pProc;
set<Proc*> translated; // Set of procs already translated
if (!progOptions.noback) {
for (pProc = prog.getFirstProc(it); pProc; pProc = prog.getNextProc(it))
{
if (!pProc->isLib() && ((UserProc*)pProc)->isDecoded()) {
// Machine dependent translation
if (progOptions.useExp) {
// Use expander for procedure
expProc->expandFunction((UserProc*)pProc);
expProc->generateFile();
// Add proc's .o file to the makefile
addSourceFile(pProc, of);
/* The following include files have been commented out as all VPO-related
* files have been removed from the UQBT distribution. If you are wanting
* to build a VPO backend and have obtained the license and code for VPO,
* then you should uncomment this section.
#if TGT==SPARC || TGT==ARM
} else if (progOptions.translateToVPO) {
// Use VPO backend
vpoBackend->expandFunction((UserProc*)pProc);
addVPOSourceFile((UserProc*)pProc, of);
#endif
*/
} else {
// use low-level C and optional JVM backends
Translate t; // Need new one for each proc
t.translate2c((UserProc*)pProc, /*speculative*/ false);
if (progOptions.translateToJava) {
// Call the JVM backend
translate2j((UserProc*)pProc);
}
// Add proc's .c file to the makefile
addSourceFile(pProc, of);
}
// Mark proc as translated
translated.insert(pProc);
}
}
}
// Now consider some speculative decodes, unless -s or -S
// Note: these are done after the ordinary procedures are done, since
// they are only done if the above find register calls
if (!progOptions.start && (progOptions.cover || prog.bRegisterCall)) {
ADDRESS start = prog.pBF->GetAddressByName("_start");
if (start) {
// Decode _start, and all its children, to find the startup
// code. Set keep to false (throw away the results), and spec
// to true (not really because we want to stop if there is an
// illegal insruction, but so that we don't decode callees that
// are outside the text section)
decodeProc(start, fe, false, true);
}
ADDRESS fini = prog.pBF->GetAddressByName("_fini");
if (fini) {
// It's also important not to decode _fini, since it may call
// C runtime functions like __do_global_dtors_aux which are not
// decoded
decodeProc(fini, fe, false, true);
}
// Hopefully, now we have all the gaps to try and decode
// We need a copy of the range object, since the decoding will
// disrupt the ranges in prog
bool change;
do {
change = false;
Coverage copy(prog.cover);
cout << "\nCoverage: "; copy.print(); cout << endl;
ADDRESS a1, a2;
COV_CIT ii;
if (copy.getFirstGap(a1, a2, ii)) {
do {
cout << "Spec decode at " << hex << a1 << endl;
change |= decodeRange(a1, a2, fe, true, true);
} while (copy.getNextGap(a1, a2, ii));
}
} while (change);
// We may have code before the start of the first range, or after
// the last range, where code might remain undecoded.
if (prog.cover.getStartOfFirst() != prog.limitTextLow)
decodeRange(prog.limitTextLow, prog.cover.getStartOfFirst(),
fe, true, true);
if (prog.cover.getEndOfLast() != prog.limitTextHigh)
decodeRange(prog.cover.getEndOfLast(), prog.limitTextHigh,
fe, true, true);
// Propagate type information some more because of the
// newly discovered functions from the spec decode
if (progOptions.typeAnalysis) {
// The number of times to loop is currently arbitary
for (int i = 0; i < 3; i++) {
// Propagate type information between procedures
interProcPropagation();
// Re-propagate between BBs
propagateBetweenBB();
}
}
if (!progOptions.noback) {
for (pProc = prog.getFirstProc(it); pProc;
pProc = prog.getNextProc(it)) {
if (!pProc->isLib() && ((UserProc*)pProc)->isDecoded()) {
if (translated.count(pProc)) {
// Don't translate a second time
continue;
}
// Machine dependent translation
if (progOptions.useExp) {
// Use expander for procedure
expProc->expandFunction((UserProc*)pProc);
expProc->generateFile();
// Add proc's .o file to the makefile
addSourceFile((UserProc*)pProc, of);
/* The following include files have been commented out as all VPO-related
* files have been removed from the UQBT distribution. If you are wanting
* to build a VPO backend and have obtained the license and code for VPO,
* then you should uncomment this section.
#if TGT==SPARC || TGT==ARM
} else if (progOptions.translateToVPO) {
// Use VPO backend
vpoBackend->expandFunction((UserProc*)pProc);
addVPOSourceFile((UserProc*)pProc, of);
#endif
*/
} else {
// Low level C
Translate t; // Need new one for each proc
t.translate2c((UserProc*)pProc, /*speculative*/ true);
if (progOptions.translateToJava) {
// Call the JVM backend
translate2j((UserProc*)pProc);
}
// Add proc's .c file to the makefile
addSourceFile((UserProc*)pProc, of);
}
}
}
}
}
// Print out fully propagated type data
if (progOptions.typeAnalysis){
printTypeInfo();
}
// Delete expander, if used
if (progOptions.useExp) {
delete expProc;
}
// (Jens) here is my hook-in for writing an interpretable file
// ie the source for the HRTL interpreter
void saveForHRTLI(Prog *prog);
saveForHRTLI(&prog);
// Done with the front end now
delete &fe;
// Finish the back end
if (!progOptions.noback)
finalOutput(of);
// Deallocate binary file object.
prog.pBF->UnLoad();
if (progOptions.cover) {
// Write a summary of remaining gaps
dispCoverage(inputName, decoder);
}
return 0; // Exit main()
}
/*==============================================================================
* FUNCTION: libraryReturnPropagation
* OVERVIEW: Reads the return type info from the library signatures
* PARAMETERS: CallRegInformation* inCallRegInfo
* RETURNS: none
*============================================================================*/
void libraryReturnPropagation(CallRegInformation* inCallRegInfo){
varType paramType;
map<Byte, UDChain*>::iterator mapIt;
// Should really only be one return value
for (mapIt = inCallRegInfo->returnReg.begin();
mapIt != inCallRegInfo->returnReg.end();
mapIt++){
paramType = INT_TYPE;
Type tempType = inCallRegInfo->calleeProc->getReturnType();
LOC_TYPE typeInfo = tempType.getType();
// Should really integrate this with libraryParamPropagation
switch(typeInfo){
case TVOID: break;
case INTEGER: paramType = INT_TYPE;
break;
case FLOATP: paramType = FLOAT_TYPE;
break;
case DATA_ADDRESS: paramType = POINTER_D;
break;
case FUNC_ADDRESS: paramType = POINTER_I;
break;
case VARARGS: return; // Don't know what to do with this yet
case BOOLEAN: break; // Treated as a integer
case UNKNOWN: break; // Assume integer
default: break; // Shouldn't get here
}
if (paramType > mapIt->second->chainType){
mapIt->second->chainType = paramType;
}
}
}
/*==============================================================================
* FUNCTION: libraryParamPropagation
* OVERVIEW: Reads the param type info from the library signatures
* PARAMETERS: CallRegInformation* inCallRegInfo
* RETURNS: none
*============================================================================*/
void libraryParamPropagation(CallRegInformation* inCallRegInfo){
const list<SemStr>& typeList = inCallRegInfo->calleeProc->getParams();
list<SemStr>::const_iterator listIt = typeList.begin();
varType paramType;
map<Byte, UDChain*>::iterator mapIt;
for (mapIt = inCallRegInfo->paramReg.begin();
mapIt != inCallRegInfo->paramReg.end();
mapIt++){
paramType = INT_TYPE;
// This will not work 100% of the time because it assumes all params are
// are registers, which is not always true. This will be fixed...
if (listIt == typeList.end()){
printf("Formal and actual parameters don't \
match up for library function %s\n",
inCallRegInfo->calleeProc->getName());
return; // parameter values doesn't really match up with
// what libraries says.
}
Type tempType = listIt->getType();
LOC_TYPE typeInfo = tempType.getType();
switch(typeInfo){
case TVOID: break; // Should never be here
case INTEGER: paramType = INT_TYPE;
break;
case FLOATP: paramType = FLOAT_TYPE;
break;
case DATA_ADDRESS: paramType = POINTER_D;
break;
case FUNC_ADDRESS: paramType = POINTER_I;
break;
case VARARGS: return; // Don't know what to do with this yet
case BOOLEAN: break; // Treated as a integer
case UNKNOWN: break; // Assume integer
default: break; // Shouldn't get here
}
if (paramType > mapIt->second->chainType){
mapIt->second->chainType = paramType;
}
listIt++;
}
}
/*==============================================================================
* FUNCTION: paramValuePropagation
* OVERVIEW: propagates param values between procedures
* PARAMETERS: CallRegInformation* inCallRegInfo
* RETURNS: none
*============================================================================*/
void paramValuePropagation(CallRegInformation* inCallRegInfo){
BB_CIT tempIt;
PBB tempCalleeBB =
(((UserProc*)(inCallRegInfo->calleeProc))->getCFG())->getFirstBB(tempIt);
list<int>::iterator paramListIt =
inCallRegInfo->calleeProc->regParams.begin();
map<Byte, UDChain*>::iterator mapIt;
for (mapIt = inCallRegInfo->paramReg.begin();
mapIt != inCallRegInfo->paramReg.end();
mapIt++){
if (paramListIt == inCallRegInfo->calleeProc->regParams.end()) {
printf("Actual and formal parameter list size doesn't match\n");
break;
}
// Get the next register based parameter
int calleeParam = 0;
do {
calleeParam = *paramListIt++;
}
while (calleeParam == -1);
list<UDChain*>* tempUDChain =
tempCalleeBB->usedDefineStruct->returnRegChainListAt(calleeParam);
if (tempUDChain == NULL){
// This would be a strange case
continue;
}
UDChain * calleeChain = tempUDChain->front();
if (calleeChain == NULL) {
// This would be a strange case
continue;
}
if (calleeChain->chainType > mapIt->second->chainType){
mapIt->second->chainType = calleeChain->chainType;
}
else {
calleeChain->chainType = mapIt->second->chainType;
}
}
}
/*==============================================================================
* FUNCTION: returnValuePropagation
* OVERVIEW: propagates return values between procedures
* PARAMETERS: CallRegInformation* inCallRegInfo
* RETURNS: none
*============================================================================*/
void returnValuePropagation(CallRegInformation* inCallRegInfo){
// For each register in returnReg, do a returnRegChainListAt
// on the list of BBBlocks in each proc. Then take only the LAST
// chain from the list of chains.
//
// Propagate between the types in the chain.
map<Byte, UDChain*>::iterator mapIt;
for (mapIt = inCallRegInfo->returnReg.begin();
mapIt != inCallRegInfo->returnReg.end();
mapIt++){
assert (inCallRegInfo->calleeProc != NULL);
list<BBBlock*>::iterator listIt;
// Do this three times to attempt to propagate completely
for (int i = 0; i < 3; i++) {
for (listIt =
inCallRegInfo->calleeProc->basicBlocksEndingWithRet.begin();
listIt !=
inCallRegInfo->calleeProc->basicBlocksEndingWithRet.end();
++listIt){
list<UDChain*>* tempUDChain =
(*listIt)->returnRegChainListAt(mapIt->first);
if (tempUDChain == NULL){
// This would be a strange case
continue;
}
UDChain * calleeChain = tempUDChain->back();
if (calleeChain == NULL) {
// This would be a strange case
continue;
}
if (calleeChain->chainType > mapIt->second->chainType){
mapIt->second->chainType = calleeChain->chainType;
}
else {
calleeChain->chainType = mapIt->second->chainType;
}
}
}
}
}
/*==============================================================================
* FUNCTION: interProcPropagation
* OVERVIEW: Propagate type information across procedures
* PARAMETERS: none
* RETURNS: none
*============================================================================*/
void interProcPropagation() {
PROGMAP::const_iterator progIt;
Proc * procTraverse;
// Iterate through all the Procs in prog
for (procTraverse = prog.getFirstProc(progIt);
procTraverse;
procTraverse = prog.getNextProc(progIt)){
if (procTraverse->isLib()){
// Skip libraries
continue;
}
// Call getCFG to get the CFG and iterate through the
// CFG for each Proc to find all the call sites
Cfg* procCfg = ((UserProc*)procTraverse)->getCFG();
BB_CIT bbIt;
PBB pBB = procCfg->getFirstBB(bbIt);
while (pBB) {
CallRegInformation* tempCallRegInfo = NULL;
if ((tempCallRegInfo =
pBB->usedDefineStruct->returnCallRegInfo()) != NULL){
if (tempCallRegInfo->calleeProc == NULL){
pBB = procCfg->getNextBB(bbIt);
continue;
}
if (tempCallRegInfo->calleeProc->isLib()){
libraryParamPropagation(tempCallRegInfo);
libraryReturnPropagation(tempCallRegInfo);
pBB = procCfg->getNextBB(bbIt);
continue;
}
paramValuePropagation(tempCallRegInfo);
returnValuePropagation(tempCallRegInfo);
}
pBB = procCfg->getNextBB(bbIt);
}
}
}
/*==============================================================================
* FUNCTION: printTypeInfo
* Overview: outputs the type info in every basic block
* Parameters: none
* Return: none
*============================================================================*/
void printTypeInfo(){
PROGMAP::const_iterator progIt;
Proc * procTraverse;
FILE * typeInfoFile;
typeInfoFile = fopen(progOptions.typeFile.c_str(), "w");
for (procTraverse = prog.getFirstProc(progIt);
procTraverse;
procTraverse = prog.getNextProc(progIt)){
if (procTraverse->isLib()){
// Skip libraries
continue;
}
fprintf(typeInfoFile, "Currently In Procedure: %s\n",
procTraverse->getName());
Cfg* procCfg = ((UserProc*)procTraverse)->getCFG();
BB_CIT bbIt;
PBB pBB = procCfg->getFirstBB(bbIt);
while (pBB) {
fprintf(typeInfoFile, "%s\n",
pBB->usedDefineStruct->outputToString());
CallRegInformation* tempPrintCallRegInfo = NULL;
if ((tempPrintCallRegInfo =
pBB->usedDefineStruct->returnCallRegInfo()) != NULL){
fprintf(typeInfoFile, "%s\n\n",
tempPrintCallRegInfo->outputToString());
}
pBB = procCfg->getNextBB(bbIt);
}
}
fclose(typeInfoFile);
}
/*==============================================================================
* FUNCTION: createUseDefineDataStructure
* OVERVIEW: Iterates through each BB in a procedure and create the
* Used/Define data structure for each one
* PARAMETERS: pProc - the procedure to be displayed
* pCfg - its CFG
* RETURNS: <nothing>
*============================================================================*/
void createUseDefineDataStruct(UserProc* pProc, Cfg* pCfg)
{
BB_CIT it;
PBB pBB = pCfg->getFirstBB(it);
/* First create the BBBlock*/
if (pBB) {
pBB->usedDefineStruct = new BBBlock();
pProc->storeParams(*(pBB->usedDefineStruct));
}
while (pBB)
{
pBB->storeUseDefineStruct(*(pBB->usedDefineStruct));
if(pBB->usedDefineStruct->returnRetInfo()){
// if it is a Ret BB, then add it to the list
// to be stored in the Proc
pProc->basicBlocksEndingWithRet.push_back(pBB->usedDefineStruct);
}
pBB = pCfg->getNextBB(it);